Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Doubt in negative numbers in binary format

Deepika Namasani
Greenhorn
Posts: 25
public class test33
{
public static void main(String args[])
{
int i = -1;
i = i >> 1;
System.out.println(i);
}
}
answer for this code is -1

since it is -1 something like this

since i is int it is 32 bit(4 byte)

10000000 00000000 00000000 00000001

but when it is >>1(signed right shift it is )

11000000 00000000 00000000 00000000

so how did -1 come

pls clarify this one
thanks

Henry Wong
author
Marshal
Posts: 21752
85
since it is -1 something like this

since i is int it is 32 bit(4 byte)

10000000 00000000 00000000 00000001

-1 = 11111111 11111111 11111111 11111111

Java like many other languages/processors uses two's complement. To negate a number you need to complement the number and add one.

Henry
[ May 24, 2005: Message edited by: Henry Wong ]

fred rosenberger
lowercase baba
Bartender
Posts: 12234
36
since it is -1 something like this

since i is int it is 32 bit(4 byte)

10000000 00000000 00000000 00000001

this last line is incorrect. to get the binary representation of a number, follow these steps:

write the positive number in binary. so for -1, we'd write 1 in binary:

00000000 00000000 00000000 00000001

now, flip every bit to it's alternate state:

11111111 11111111 11111111 11111110

11111111 11111111 11111111 11111111

now that we have -1 in binary, we can do the bit shift. move everything over one bit, keep the sign bit, and we get:

11111111 11111111 11111111 11111111

which is -1.
[ May 25, 2005: Message edited by: fred rosenberger ]

amit taneja
Ranch Hand
Posts: 813

but can u pls tell me that why we do
two complement for getting nagative...

why don't

-1 is like 10000000 00000000 00000000 00000001

as we have negative signbit (1 on leftmost) and rest of the no.

then why we complement the bits and add one

i think we add one becasue negative value has one no. more capacity w.r.t positive no.

but why complements ?
plss explain.

Steven Bell
Ranch Hand
Posts: 1071
In code tags for formating

Edwin Keeton
Ranch Hand
Posts: 214
The main reason for using twos complement to represent negative numbers is to make it easy to add (and subtract) two signed numbers. Adding 17 and -4 looks like this in binary (showing only 8 bits to keep it short):

0001 0001 (17)
+ 1111 1100 (-4)

= 0000 1101 (13)

It is more expensive to basic arithmetic without using twos complement.

The reason there is one more negative value to a signed integer type is because we use twos complement, not the other way around.

Deepika Namasani
Greenhorn
Posts: 25
Thank you

fred rosenberger
lowercase baba
Bartender
Posts: 12234
36
and don't forget the classic example of

1000...0000

which would translate to -0.