aspose file tools
The moose likes Beginning Java and the fly likes Doubt   with  bit  shifting,Please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt   with  bit  shifting,Please help" Watch "Doubt   with  bit  shifting,Please help" New topic

Doubt with bit shifting,Please help

vinayak manda
Ranch Hand

Joined: Jul 27, 2004
Posts: 31
I was learning about right shift operator in one of the corey's links

Right shifting the positive number is ok,but with negative number,
I had a doubt.Let me interpret what I have understood.

With respect to the most significant number in the right side of the binary number to be shifted,if it is 0 then the number is positive and we put 0's from the left,and if it is 1 then the number is negative,and we put 1's from the left.So let's say...


To represent 13 as negative ,we use 2's complement...

00000000 00000000 00000000 00001101 (The value of 13)
11111111 11111111 11111111 11110010 (We flip 0's to 1's and 1's to 0's)
00000000 00000000 00000000 00000001 (We add the value of 1 )
11111111 11111111 11111111 11110011 (This result represents -13)

Now as -13(binary form) has 1 in its sign bit,therfore when shifting this binary number to the right we add 1 from the left.Right!!

This turns up to
11111111 11111111 11111111 11111001 ( The result)

To evaluate this,we do it as
-2(pow of 31) + 2(pow of 30) .....+2(pow of 3)+2(pow of 0) (I wanted to verify is this the way we need to evaluate the number ?).
If yes, then the answer has to be -7.
But I'am not getting my answer right.
I have -2(pow of 31) as -2147483648 and by adding numbers from
2(pow of 30) to 2(pow of 3) and 2(pow of 0) I get 2147483644.
So,(-2147483648+2147483644) gives me -4 rather than -7,why? am I missing something here.

Please help.
Rovas Kram
Ranch Hand

Joined: Aug 08, 2003
Posts: 135

I'm curious why you don't do the 2's complement in reverse. For example,

11111111 11111111 11111111 11111001 (a negative a number)
11111111 11111111 11111111 11111000 (subtract 1)
00000000 00000000 00000000 00000111 (the magitude of the negative number)

The leading 1 says that the number is negative. It says nothing about the numbers magnitude; for that you must do the transformation.
vinayak manda
Ranch Hand

Joined: Jul 27, 2004
Posts: 31
Wow!!! That was so easy ,,,,,
Thank u so much for the clarification...
I agree. Here's the link:
subject: Doubt with bit shifting,Please help