Reputation:
How can I/computer tell if binary numbers are signed or unsigned integers? Eg the binary number 1000 0001 can both be interpreted as -128, if signed, and 129, if unsigned.
One advantage of using unsigned integers in languages like C (as I understand it) is that it enables you to use larger integers due to the extra bit earned by not defining the sign. However, it seems to me that you need something, somewhere, that keeps track of whether the first bit represents a sign or is just a part of what describes the magnitude of the number.
Upvotes: 1
Views: 8327
Reputation: 599
Computer doesn't need to know about sign. It's about how to print the number. Arithmetic works fine and it doesn't mind if it is signed or unsigned. When it is trimmed to needed length, the result is correct.
Example multiplying on 8-bit:
// negative times negative
254 * 254 = 64516 // decimal unsigned - it's equal to 4
((-2) * (-2)) = 4 // decimal signed
1111 1110 * 1111 1110 = 1111 1100 0000 0100 // binary - 0000 0100
// negative times positive
254 * 2 = 508 // decimal unsigned - it's equal to (-4)
-2 * 2 = -4 // decimal signed
1111 1110 * 0000 0010 = 0000 0001 1111 1100 // binary - 1111 1100
So it's up to you how you represent 1111 1100. If you are using language like Java, it doesn't support unsigned number types.
Upvotes: 1
Reputation: 1853
In memory the computer will store the binary representation as 10000001 whether it is unsigned or signed. Just by looking at the number in memory it would be impossible to classify the binary number as being signed or unsigned. We need instructions to tell whether we should be treating this number as unsigned or signed. This is where the compiler comes in. As a programmer, you will designate that number as signed as unsigned. The compiler will translate the code written and generate the desired instructions for that number. Note that depending on the programming language, there may be different methods of generating these instructions. The important part to remember is that there is no difference in the binary number in memory, only in how the programmer communicates how this number should be treated to the compiler.
Upvotes: 5
Reputation: 3520
The variable type keeps track of whether it's signed or unsigned. The actual value in the register cannot tell you (as you would need an extra bit to store that information). You can turn on warnings that warn against unsigned to singed conversions, and then the compiler will yell at you if you accidentally assigned an unsigned value to a signed one or vice versa.
Upvotes: 1