This week's book giveaway is in the Android forum. We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line! See this thread for details.

given i=-1 -1>>31; what I have done after reading a post here first of written one as 00000000 00000000 00000000 00000000 00000001 then I inverted all bits 11111111 11111111 11111111 11111110 then I add one to it 11111111 11111111 11111111 11111111 then when i shifted it to right 31 bit 00000000 00000000 00000000 00000001 now the value is 1 Answer is -1 which is correct where I made the mistake?

Payal, This is the way you have to go about byte shifting <pre> 1 ===> 0000 0000 0000 0000 0000 0000 0000 0001 ~(inverse) ===> 1111 1111 1111 1111 1111 1111 1111 1110 Add 1 ===> 1 -1 ===> 1111 1111 1111 1111 1111 1111 1111 1111 >> 31 bits ===> 1111 1111 1111 1111 1111 1111 1111 1111 </pre> Note that, while doing a right shift you have to take fill the places with the sign bit in the left.In this case it is 1 and not 0. So the result is -1 and not 1. Hope this helps, Sandeep SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)

Desai Sandeep
Ranch Hand

Joined: Apr 02, 2001
Posts: 1157

posted

0

Rajani, -1 is not represented as 1000 0000 0000 0000 0000 0000 0000 0001 in binary format! -- Sandeep

I am sorry ,I used wrong words!!! Of course that is not a binary represetation but I thought that will help to solve the questions in the exam point of view!!! Thanx Rajani

Originally posted by Desai Sandeep: Rajani, -1 is not represented as 1000 0000 0000 0000 0000 0000 0000 0001 in binary format! -- Sandeep

Hi Payal , Just my addition When you are shifthing right ( >> ) --- the leftmost(top) bits exposed by the right shift are filled in with the previous contents of the top bit & not just zero's . We would've got the answer as 1 if we were using " >>> " instead of " >> " . " >>> " always shifts zero's into the high order bit . This should help you explain the answer . The interesting thing about your question is that no matter how much you use " >> " to shift -1 to the right the result would always be -1 . Hope hat helps [This message has been edited by Ashish Hareet (edited July 27, 2001).]