我们在该文中已经分析了关于字符指针强制类型转换为uint16_t/uint8_t型指针,不会越限的现象,这里我们做一下具体分析:
char ch[4]={0xAA,0x11};printf("%d %d\n",*ch,*(ch+1));printf("%x %x\n",*ch,*(ch+1));printf("uint8_t:%d %d\n",*(uint8_t*)ch,*(uint8_t*)(ch+1));//十进制printf("uint8_t:%x %x\n",*(uint8_t*)ch,*(uint8_t*)(ch+1));//十六进制printf("uint16_t:%d %d\n",*(uint16_t*)ch,*(uint16_t*)(ch+1));//十进制printf("uint16_t:%x %x\n",*(uint16_t*)ch,*(uint16_t*)(ch+1));//十六进制qDebug()<<"****************************************";char j =0xAA;//170 = 128+42 =-(128-42) = -86;void *q = (void*)j; //1111 1111 1111 1111 1111 1111 1010 1010uint8_t m = (uint8_t)j;//1010 1010uint16_t n =(uint16_t)j;//1111 1111 1010 1010uint32_t l = (uint32_t)j;qDebug()<<"char:"<<j;qDebug()<<"void*:"<<q;qDebug()<<"uint8_t:"<<m;qDebug()<<"uint16_t:"<<n;qDebug()<<"uint32_t:"<<l;
分析:
1)0xAA 存储在char 类型中,发生越限,实际上是存储的是 -86。
printf("%x %x\n",*ch,*(ch+1)); //相当于把一个字节的数据转换成4个字节的数据:即是-86的四字节十六进制数。
2)86的二进制: 0101 0110------->转换成4字节:0000 0000 0000 0000 0000 0000 0101 0110
3)-86的二进制:1010 1010 ---->转换成4字节:1111 1111 1111 1111 1111 1111 1010 1010(符号位不变,取反+1)
4)转换成uint8_t :相当于把 1010 1010 当成一个uint8_t ,即是AA/170;
最正确的写法是,使用uchar ,而不是char,如下程序所示:
uchar ch[4]={0xAA,0x11}; //-----》使用ucharprintf("%d %d\n",*ch,*(ch+1));printf("%x %x\n",*ch,*(ch+1));printf("uint8_t:%d %d\n",*(uint8_t*)ch,*(uint8_t*)(ch+1));//十进制printf("uint8_t:%x %x\n",*(uint8_t*)ch,*(uint8_t*)(ch+1));//十六进制printf("uint16_t:%d %d\n",*(uint16_t*)ch,*(uint16_t*)(ch+1));//十进制printf("uint16_t:%x %x\n",*(uint16_t*)ch,*(uint16_t*)(ch+1));//十六进制qDebug()<<"****************************************";uchar j =0xAA;//170 = 128+42 =-(128-42) = -86; //-----》使用ucharvoid *q = (void*)j; //1111 1111 1111 1111 1111 1111 1010 1010uint8_t m = (uint8_t)j;//1010 1010uint16_t n =(uint16_t)j;//1111 1111 1010 1010uint32_t l = (uint32_t)j;qDebug()<<"char:"<<j;qDebug()<<"void*:"<<q;qDebug()<<"uint8_t:"<<m;qDebug()<<"uint16_t:"<<n;qDebug()<<"uint32_t:"<<l;