Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# shifting problem

payal sharma
Ranch Hand
Posts: 57
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

Desai Sandeep
Ranch Hand
Posts: 1157
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
-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
Posts: 1157
Rajani,
-1 is not represented as
1000 0000 0000 0000 0000 0000 0000 0001
in binary format!
-- Sandeep

Mini Pilla
Ranch Hand
Posts: 112
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

Ashish Hareet
Ranch Hand
Posts: 375
Hi Payal ,
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 .
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).]

Bill Tripper
Greenhorn
Posts: 24
Originally posted by payal sharma:
given
i=-1
-1>>31;

Am I missing something here? The way I figure this is:
i=-1
-1>>31;
is the same as
i=-1 -1>>31;
or
i = (-1) - (1>>31);
or
i = (-1) - 0
or
i = -1
Bill

Jon Miller
Greenhorn
Posts: 7
From the code originally submitted I would have to agree with the last posting!