What happens if I assign a negative value to an unsigned variable?

前端 未结 6 980
旧巷少年郎
旧巷少年郎 2020-11-22 07:31

I was curious to know what would happen if I assign a negative value to an unsigned variable.

The code will look somewhat like this.

unsigned int nVa         


        
6条回答
  •  天涯浪人
    2020-11-22 08:24

    When you assign a negative value to an unsigned variable then it uses the 2's complement method to process it and in this method it flips all 0s to 1s and all 1s to 0s and then adds 1 to it. In your case, you are dealing with int which is of 4 byte(32 bits) so it tries to use 2's complement method on 32 bit number which causes the higher bit to flip. For example:

    ┌─[student@pc]─[~]
    └──╼ $pcalc 0y00000000000000000000000000000101      # 5 in binary
            5                       0x5                     0y101
    ┌─[student@pc]─[~]
    └──╼ $pcalc 0y11111111111111111111111111111010      # flip all bits  
          4294967290      0xfffffffa      0y11111111111111111111111111111010
    ┌─[student@pc]─[~]
    └──╼ $pcalc 0y11111111111111111111111111111010 + 1  # add 1 to that flipped binarry
          4294967291      0xfffffffb      0y11111111111111111111111111111011
    

提交回复
热议问题