how unsigned integer store negative numbers

phanihup's Avatar, Join Date: Jun 2012
Newbie Member
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?
xpi0t0s's Avatar, Join Date: Aug 2004
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.

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.
xpi0t0s's Avatar, Join Date: Aug 2004
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.
unsigned int i=-9;