字符型数据0x80强转成unsigned int为什么会扩展符号位?

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("%x\n", (unsigned int)(unsigned char)0x80);
    printf("%x\n", (unsigned int)(signed char)0x80);
    
    return 0;
}

输出:

80
ffffff80

第一个输出80可以理解,毕竟是从0x80转换为无符号int
第二个输出ffffff80我无法理解,从1字节数据扩展为4字节数据,并且是扩展到无符号类型,为什么符号位也跟着扩展了?

P.S. C/C++中输出结果一致

阅读 2.3k
1 个回答

负数转 unsigned 就是这样规定的啊。

原话是这样的(C++17)

conv.integral:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation).  — end note ]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题