C++ 类型转化

string 转为char*

const char *a;//必须const 因为“hello”存在常量区,为只读
string str="hello";//str[1]='s'; pass  
a=str.c_str();//a[1]='s';fail    报错:只读,指针指向常量区

char* 转为int

    char *a;
    a="11";
    int b=atoi(a);
    cout<<b<<endl;//out:11

int转为string

int a=11;
string str=to_string(a);//C++11 开始支持

char* 转为string

char* a="hello";
string str=a;       //直接赋值

sstream

    stringstream str;
    string s="123";
    int i;
    str<<s;
    str>>i;
    cout<<i<<endl;

小端存储

X86中,都是小段存储,即低位存储在低地址单元
例如:
0x12345678 存放在0x00000000,0x00000001,0x00000002,0x00000003地址单元中,则低位数据0x78存储在0x00000000低位地址单元中

补码

绝对值取反加一
原码为补码的补码

类型转化问题

int main(){
    unsigned int a=0xfffffff7;
    unsigned char b=(unsigned char)a;
    char *c=(char*)&a;
    printf("%08x,%08x",b,0xf7); //out:0x000000f7,0xfffffff7
}

关于b

int有4个字节,char1个字节,强制转换导致数据丢失,只截取了最低位地址单元中的数据0xf7.因为b为unsigned所以输出8字符16进制为0x000000f7.

关于c

因为*c是有符号的0xf7,计算机中认作为-9(9为0xf7取反加一),-9用printf输出8字符16进制为反码,即0xfffffff7

猜你喜欢

转载自blog.csdn.net/weixin_41127779/article/details/82150598
今日推荐