Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How computer distinguish an integer is signed or unsigned?

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.

like image 773
viperchaos Avatar asked Jun 05 '12 07:06

viperchaos


People also ask

How do you know if a byte is signed or unsigned?

If a signed byte is assigned, then the resulting integer is sign extended (i.e., 0xff becomes 0xffffffff). If an unsigned byte is assigned, then the resulting integer is zero extended (i.e., 0xff becomes 0x000000ff).

How can you tell the difference between signed and unsigned integers?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

Does a computer know the difference between signed and unsigned binary numbers?

Short version: it doesn't know. There's no way to tell. If 1111 represents -7, then you have a sign-magnitude representation, where the first bit is the sign and the rest of the bits are the magnitude. In this case, arithmetic is somewhat complicated, since an unsigned add and a signed add use different logic.

How do you know if an integer is signed?

Signed integers are numbers with a “+” or “-“ sign. If n bits are used to represent a signed binary integer number, then out of n bits,1 bit will be used to represent a sign of the number and rest (n - 1)bits will be utilized to represent magnitude part of the number itself.


1 Answers

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.

like image 79
Sjoerd Avatar answered Sep 22 '22 02:09

Sjoerd