简体   繁体   English

有符号与无符号比较

[英]Signed vs Unsigned comparison

#include <iostream>

int main()
{
    signed int a = 5;
    unsigned char b = -5;
    unsigned int c = a > b;

    std::cout << c << std::endl;
}

This code prints 0 . 此代码显示0

Can anyone please explain what is happening here? 谁能解释一下这里发生了什么? I am guessing that compiler converts a and b to same type( unsigend int maybe) and compares them. 我猜编译器将ab转换为相同的类型(可能是unsigend int )并进行比较。

Let's see how the computer stores the value b: 让我们看看计算机如何存储值b:
5 is 00000101 , so -5 will be 11111011 , so, when you convert it to unsigned char , it will became some positive number with value 11111011 in binary, which is larger than 00000101 . 500000101 ,所以-5将是11111011 ,因此,当您将其转换为unsigned char ,它将变成一些正数值,二进制值为11111011 ,大于00000101
So, that's why a = 00000101 is smaller than b (0 means false). 因此,这就是为什么a = 00000101小于b (0表示错误)的原因。

It is printing 0 because a < b and 0 means false. 它正在打印0因为a < b0表示false。 The type of b is unsigned so it cannot hold negative numbers. b的类型是unsigned因此它不能包含负数。 Because of that -5 becomes 251 which is grater than 5 . 因此-5变成251 ,比5更大。

Lets go to the third line in main c take the value of 0 because a is not greater than b . 让我们转到main c的第三行,取0值,因为a不大于b This is because in C zero is considered false and everything then else is true. 这是因为在C中零被认为是假的,而其他所有东西都为真。

With regards to b . 关于b Most platforms store negative integers using 2s complement format. 大多数平台使用2s补码格式存储负整数。 So when we negate an number we flip all the bits and add 1. So -5 unsigned become 0xfa which is greater than 5. 因此,当我们对数字求反时,我们会将所有位翻转并加1。因此-5 unsigned变为大于5的0xfa。

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

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