char和int的问题?
5:设a为char类型,b为int类型,那么a = (char)b等效于 a = b & 0xff; √
6:设a为char类型,b为int类型,那么a = (char)b等效于 a = *(char *)&b; ×
希望高手帮忙分析一下。
[解决办法]
前面那个有点问题,重发一遍
int型占4字节,char型占1字节,数据结构如下,一个字节占8位二进制
b:
¦8bits ¦ ¦8bits ¦ ¦8bits ¦ ¦8bits ¦
xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
a:
¦8bits ¦
xxxxxxxx
0xff是十六进制,换算成10进制就是255 = 2^8 - 1,二进制的表现形式是:
¦8bits ¦ ¦8bits ¦ ¦8bits ¦ ¦8bits ¦
00000000 00000000 00000000 11111111
b & 0xff进行了按位与的运算,就是2进制上相同位置的数字都是1的时候,结果才是1
因此 b & oxff 实际上对b进行了截断,因为0xff除了最后8为是1以外,其他都是0,
因此,b & 0xff的结果是
00000000 00000000 00000000 xxxxxxxx
而这最后的8位是和b的最后8位一样的,因为0 & 1 = 0, 0 & 0 = 1, 1 & 1 = 1;
(char)b的意思就是对b进行强制转换,对b的数据进行截断,取的也是b对最后8位
因此 a = (char)b等效于 a = b & 0xff;
[解决办法]
int b = 0x30313233; // 0x30 is ascii for '0', and so onchar a = (char)b; // cast from int to char: get the "last" byte 0x33 // i.e. b & 0xffchar a = *(char*)&b; // get the byte pointed by the "&b" // cast to make "&b" a char pointerbin-endian:base_address + 3: |0x33| base_address + 2: |0x32| base_address + 1: |0x31| base_address + 0: |0x30| <-- &b point herelittle-endian:base_address + 3: |0x30| base_address + 2: |0x31| base_address + 1: |0x32| base_address + 0: |0x33| <-- &b point heredefault, &b is a pointer of int and 4 bytes will be interpreted;by casting &b into a pointer of char, only 1 byte is interpreted.