关于隐式类型转换

$ cat a.cpp
#include
#include

int main()
{
        char str[64] = "123456";
        printf("%s\n", str);

        printf("%d\n", sizeof(long));

        char c = 0xF0;
        int i = c;
        printf("%d\n", i);
        printf("%x\n", i);

        char str1[8] = {'\0'};
        str1[0] = 0xF0;
        str1[1] = 0x00;

        //先整型提升 再隐式转换 char ---> int ---> long
        long num = (str1[0] << 8) | str1[1];
        printf("%ld\n", num);
        printf("%x\n", num);

        //先强制类型转换 再整型提升 再隐式转换 char ---> unsigned char ---> int ---> long
        long num1 = ((unsigned char)str1[0] << 8) | (unsigned char)str1[1];
        printf("%ld\n", num1);
        printf("%x\n", num1);

        //先整型提升 再隐式转换 char ---> int ---> long
        long num2 = ((str1[0] & 0x0FF) << 8) | (str1[1] & 0x0FF);
        printf("%ld\n", num2);
        printf("%x\n", num2);

        long l = 0xF0 << 8 | 0x00;
        printf("%ld\n", l);
        printf("%x\n", l);

        return 0;

}


$ ./a.out
123456
8
-16
fffffff0
-4096
fffff000
61440
f000
61440
f000
61440
f000


注意:在进行自动类型转换的时候,如果原来的数是无符号数,那么在扩展的时候,高位填充的是0;如果是有符号数,那么高位填充的时符号位!

你可能感兴趣的:(关于隐式类型转换)