This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.

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

-13>>=1

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.

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

posted

0

Wow!!! That was so easy ,,,,, Thank u so much for the clarification...