Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Right shift question

Nikhil Bansal
Ranch Hand
Posts: 60
Hi Ranchers,

A very simple ques .

What should be the value of i

i = -1 >> 2;

I think -1 = 10000000 00000000 00000000 00000001 in binary.
Then by right shift it should be 11100000 00000000 00000000 00000000 which is equal to 3758096384 in decimal.

When I run the program, then I get i as -1.

Regards

Nikhil Bansal

wise owen
Ranch Hand
Posts: 2023

I think -1 = 10000000 00000000 00000000 00000001 in binary.

-1 = 11111111 11111111 11111111 11111111

Praveen Babu
Ranch Hand
Posts: 138
The negative numbers are represented in 2's compliment notation
2's compliment = flip all digits + 1

so,

1 = 00000000 00000000 00000000 00000001

and, -1 = flip all digits + 1

that is,

11111111 11111111 11111111 11111110
00000000 00000000 00000000 00000001
____________________________________
11111111 11111111 11111111 11111111

and hence, the number will remain the same if you right shift it by any number.
[ November 01, 2006: Message edited by: Praveen Babu ]

Andy Morris
Ranch Hand
Posts: 78
Bit shifting is not in the 1.5 exam in case you didn't know.