Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

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

#include <stdio.h>

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

输出:

80
ffffff80

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

负数转 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?]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...