类型转换
代码如下
int main(int argc, const char * argv[]) {
int a = 0xABCD07; // 0000 0111 最低位的一个字节
int b = 0xABCD77; // 0111 0111
int c = 0xABCD87; // 1000 0111
int d = 0xABCDF7; // 1111 0111
char *a1 = (char*)&a;
unsigned char *a2 = (unsigned char*)&a;
char *b1 = (char*)&b;
unsigned char *b2 = (unsigned char*)&b;
char *c1 = (char*)&c;
unsigned char *c2 = (unsigned char*)&c;
char *d1 = (char*)&d;
unsigned char *d2 = (unsigned char*)&d;
printf("%08x, %08x\n", *a1, *a2); //注意char*转换时符号位扩展
printf("%08x, %08x\n", *b1, *b2);
printf("%08x, %08x\n", *c1, *c2);
printf("%08x, %08x\n", *d1, *d2);
return 0;
}
运行结果
注意char* 和 unsigned char*的打印结果的不同
对于一个char类型的变量来说,最高位是符号位,低7位才是数据位,所以,对于上边的c和d,最低一字节的第八位是1,所以对于printf用%08x的时候,c1和d1会对最高位的符号位1做符号位扩展,所以打印出来的会是fffffff7.