C++中有符号数与无符号数相互转换关系,多字节数与少字节数相互转

2019-03-23  本文已影响0人  hplllrhp

其实总结可能就是几句话

源对象是有符号数的转换

少字节数转成多字节数(如char->(unsigned) short等)

多字节数转成少字节数(如short->(unsigned) char等)

源对象是无符号数的转换

少字节数转成多字节数(如char->(unsigned) short等)

多字节数转成少字节数(如short->(unsigned) char等)

#include <iostream>
using namespace std;

int main()
{
    //符号位1,有符号数多字节转无符号少字节
    //结果:去掉高位,只保留无符号的字节数
    short s_short = 0x8199;
    cout<<hex<<s_short<<endl;
    cout<<s_short<<endl;
    char s_char = s_short;
    cout<<hex<<s_char<<endl;
    unsigned char u_char = s_short;
    cout<<hex<<u_char<<endl;
    //符号位1,有符号数多字节转无符号少字节

    //符号位1,有符号数少字节转无符号多字节
    char s_char1 = 0x99;
    cout<<hex<<(int)s_char1<<endl;
    unsigned short s_short1 = s_char1;
    cout<<hex<<s_short1<<endl;
    //符号位1,有符号数少字节转无符号多字节

    //无符号转有符号,小转大,高位补充0
    unsigned char uchar2 = 0x99;
    cout<<"(int)uchar2: "<<(int)uchar2<<endl;
    cout<<"(unsigned int)uchar2: "<<(unsigned int)uchar2<<endl;
    //无符号转有符号,小转大,高位补充0
    //大转小
    unsigned short u_short2 = 0x9999;
    cout<<"(unsigned char)u_short2: "<<(unsigned char)u_short2<<endl;
    cout<<"(char)u_short2: "<<(char)u_short2<<endl;
}

上一篇下一篇

猜你喜欢

热点阅读