How computer distinguish an integer is signed or unsigned?

谁都会走 提交于 2019-12-04 10:40:52

问题


Two's complements is set to make it easier for computer to compute the substraction of two numbers. But how computer distinguish an integer is signed integer or unsigned integer? It's just 0 and 1 in its memory.

For exmaple, 1111 1111 in the computer memory may represent number 255 but also can represent -1.


回答1:


Signed and unsigned use the same data, but different instructions.

The computer stores signed and unsigned integers as the same data. I.e. 255 and -1 are the same bits. However, you tell the compiler what type the variable has. If it is signed, the compiler uses signed operators for manipulating the variables (e.g. IDIV) and when unsigned, it uses another instruction (e.g. DIV). So the compiler makes a program which tells the CPU how to interpret the data.




回答2:


It does not distinguish them. But with the complement, the computation is the same :

Below, d will be appended to decimal numbers, and b to binary numbers. Computations will be on 8 bits integers.

-1d + 1d = 1111 1111b + 1b = 1 0000 0000b

But since we overflowed (yep, that's 8 0s and a 1 on a 8 bits integers), the result is equal to 0.

-2d + 1d = 1111 1110b + 1b = 1111 1111b = -1d

-1d + 2d = 1111 1111b + 10b = 1 0000 0001b (this overflows) = 1b = 1d

-1d + -1d = 1111 1111b + 1111 1111b = 1 1111 1110b (this overflows) = 1111 1110b = -2d

And if you consider these operations on unsigned (binary values will be unchanged) :

255d + 1d = 1111 1111b + 1b = 1 0000 0000b (this overflows) = 0d

254d + 1d = 1111 1110b + 1b = 1111 1111b = 255d

255d + 2d = 1111 1111b + 10b = 1 0000 0001b (this overflows) = 1b = 1d

255d + 255d = 1111 1111b + 1111 1111b = 1 1111 1110b (this overflows) = 1111 1110b = 2d

Unsigned versus signed is thus just a visual representation of unsigned, only used when displaying to a human :-)



来源:https://stackoverflow.com/questions/10893232/how-computer-distinguish-an-integer-is-signed-or-unsigned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!