I know there are various pages written on this topic but i am not getting a very simple answer and hence getting confused
when i store 4 in an integer variable it is definitely stored in binary format i.e no 1's and 2's complement is used and the standard conversion way of decimal to binary is used
but when i store -4 why 2's complement is used??
I know how to find 2's complement of a number..... my question is WHY 2'S COMPLEMENT???

How else would you store negative values without having one or more mapped twice?
This and the feature that you can easily add/sub and check of correctness is why.

No, every integer in Java™ except a char uses two's complement. Exactly half the possible values are reserved for negative numbers and exactly half for non-negative numbers. The value of the non-negative numbers is the same as an unsigned number would be, but that is still two's complement.

You are probably better to learn about how computers store data first. this is not really a Java question.

Just to get you started Java stores an int as a signed 32 bit value.

ie the decimal 1 will be stored (at the bit level) as:
00000000 00000000 00000000 00000001 (spaces used purely for formatting)

the decimal minus 1 (-1) is stored like this:
11111111 11111111 11111111 11111111

See if you can figure out why.

Also, why is it that if Java stored numbers as unsigned then the maximum value would double?

My examples assume that your computer uses twos complement.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033

22

posted

0

Angus Comber wrote: . . . My examples assume that your computer uses twos complement.

Not twos complement, but two's complement. And I have added [tt] tags to your numbers to improve the spacing. It changes 11111111 to 11111111 and 10101010 to 10101010.

If he is using Java™ then he is definitely using two's complement arithmetic for all integers except the char.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033

22

posted

0

Because two's complement is the only representation of negative numbers which permits the same chip to be used for addition and subtraction.
Because two's complement allows us to fit 256 different numbers into 8 bits whereas S&M only fits 255 numbers into the same 8 bits.