Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   how unsigned integer store negative numbers (http://www.go4expert.com/forums/unsigned-integer-store-negative-t28637/)

 phanihup 29Jun2012 12:00

how unsigned integer store negative numbers

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 30Jun2012 14:15

Re: how unsigned integer store negative numbers

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.

 xpi0t0s 30Jun2012 14:18

Re: how unsigned integer store negative numbers

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;`

 All times are GMT +5.5. The time now is 19:11.