简体   繁体   English

将带符号的char转换为C中的unsigned int

[英]Cast signed char to unsigned int in C

Can anyone explain to me why the following code outputs -50 even though it is being cast to an unsigned int? 任何人都可以向我解释为什么下面的代码输出-50即使它被转换为unsigned int?

int main()
{
  signed char byte = -50;
  unsigned int n;

  n = (unsigned int) byte;

  printf("n: %d", n);
}

output: -50 输出:-50

The cast is correct, but you are printing it incorrectly. 演员是正确的,但你打印错误。 %d in printf() is for int , change it to: printf() %d用于int ,将其更改为:

printf("n: %u", n);

Assigning -50 to unsigned int causes the integer to wrap around, and this wrapped around unsigned int has the same bits set as the signed int corresponding to -50 in the twos complement representation that is used by almost every computer. -50分配给unsigned int会导致整数回绕,并且包含unsigned int这个位与在几乎每台计算机使用的二进制补码表示中对应于-50signed int设置相同的位。

Now, printf is a function with a variable number of arguments that it interprets according to the format string. 现在, printf是一个具有可变数量参数的函数,它根据格式字符串进行解释。 The format %d is for signed int s and printf has no way of knowing that the corresponding argument is actually an unsigned int (because you told it otherwise). 格式%d用于signed intprintf无法知道相应的参数实际上是unsigned int (因为你告诉它)。 So the bits get interpreted as though it were signed int and you get -50 . 所以这些位被解释为好像是signed int并且你得到-50

With your statement: 随你的声明:

printf("n: %d", n); 

you are casting it to "Signed decimal integer" 你把它投射到“有符号十进制整数”

if you try 如果你试试

std::cout<<n<<std::endl;

you will see that you won't get -50 你会看到你不会得到-50

Even with printf("n: %u", n); 即使是printf("n: %u", n); , you are not going to get 50 . ,你不会得到50

see the link int to unsigned int conversion 请参阅链接int到unsigned int转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM