hi! my doubt is how unsigned integers store negative numbers?
if i write ,int i=-9 then how -9 is stored in i(8 bit).
if we again print the value in i we won't get -9.but we get some larger number.why it so?
|
Mentor
|
![]() |
| 30Jun2012,14:15 | #2 |
|
They don't. Unsigned integers are unsigned, by definition, and therefore always positive.
If you try then what will happen is that the bit pattern of -9 will be stored in the integer and interpreted as a positive number. Negative numbers are stored in two's complement, which is like 1's complement (where you flip all the bits) but then you add 1. 00001001=9 11110110=1's complement of 9 11110111=2's complement of 9 So if this is put into unsigned 8-bit storage, then the result will be interpreted as 247. |
|
Mentor
|
![]() |
| 30Jun2012,14:18 | #3 |
|
By the way, int i=-9 defines a signed integer by default (unless your compiler has a flag that changes that default behaviour). For unsigned integers you need to specify the unsigned keyword, i.e.
Code:
unsigned int i=-9; |

