# 2's complement

Rameshwar Soni

Ranch Hand

Posts: 247

posted 4 years ago

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???

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???

Campbell Ritchie

Sheriff

Posts: 48940

60

posted 4 years ago

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.
Angus Comber

Ranch Hand

Posts: 90

posted 4 years ago

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:

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

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.

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

Posts: 48940

60

posted 4 years ago

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

Not twos complement, but two's complement. And I have added [tt] tags to your numbers to improve the spacing. It changes 11111111 toAngus Comber wrote: . . . My examples assume that your computer uses twos complement.

`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

Posts: 48940

60