有符号数转换中"符号位扩展"

来源:互联网 发布:javascript call apply 编辑:程序博客网 时间:2024/06/01 10:13



int main()
{
    unsigned short temp1 = 65535;
    short temp2 = temp1;
    unsigned short temp3 = (unsigned short)temp2;
    unsigned short temp4 = temp2;
    int temp5 = temp2;
    unsigned int temp6 = temp2;
    unsigned long temp7 = temp2;
    int temp8 = (unsigned short)temp2;
    short temp9 = temp2;
    printf("temp1 = %d\n temp2 = %d\n temp3 = %d\n temp4 = %d\n temp5 = %d\n temp6 = %d\n temp7 = %d\n temp8 = %d\n temp9 = %d\n",
     temp1,temp2,temp3,temp4, temp5,temp6,temp7,temp8,temp9);
    return 0;
}
//改程序的输出结果
//temp1 = 65535
//temp2 = -1
//temp3 = 65535
//temp4 = 65535
//temp5 = -1
//temp6 = -1
//temp7 = -1
//temp8 = 65535
//temp9 = -1;


//根据结果也就是说,无符号符号数据是可以存储在有符号型变量内存中的,
//而且有例子在内存块长度一样时,不用强转,直接赋给无符号变量时也可行
//上述事实可以解释为内存块不变,采用不同的解码方式解出不同的数据
//但是读出来的时候要注意,如果有符号转无符号一定要强转(这句话不明白)
//之所以上例unsigned int输出-1,我并不是很清楚




short temp2 = temp1;
...
unsigned int temp6 = temp2;
先不管temp2的值是多少,上面就是short符号位扩展到int,然后再从int转unsigned int的问题。short是有符号类型,先进行符号位扩展(假设short为16位,int/unsigned int为32位)
1. short为正数,则最高位为0,当从16位扩展到32位int时,扩展的高16位用0填充,即将符号位0进行扩展,这样扩展后的32位整数和原来的整数值是一样的。
2. short为负数,则最高位为1,当从16位扩展到32位int时,扩展的高16位用1填充,即将符号位1进行扩展,这样扩展后的32位整数和原来的整数值是也是一样的。
即上面的代码等效于:
short temp2 = temp1;//temp2为-1(11111111 11111111)
...
int tempInt = temp2; //符号位扩展,tempInt也为-1(11111111 11111111 11111111 11111111)
unsigned int temp6 = tempInt;//将(11111111 11111111 11111111 11111111)解释为无符号


原创粉丝点击