This week's book giveaway is in the Other Languages forum.We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Problem in Shifting Operators

ankur rathi
Ranch Hand
Posts: 3830
I have no problem with shift operators when i use whole process ( first convert number to binary then shift .... ) . I just need more clarification on shortcuts ...

It is mention in 3rd chapter of K&B book that :

left shifting of an number n by s bit ( n << s ) is equal to n*2^s ( where ^ is power )
it is ok .

right shifting of an number n by s bit ( n >> s ) is equal to n/2^s .
but in this if suppose n is not completely devidable by 2^s then what would be the answer .

ex : 5>>2
5 : 0000 0000 0000 0000 0000 0000 0000 0101
after shift : 0000 0000 0000 0000 0000 0000 0000 0001 that is 1 .
with shortcut : 5/4 => ??
it seems that remainder is the output ( 5%4 = 1 )

but after taking amother example : -5>>2
5 : 0000 0000 0000 0000 0000 0000 0000 0101
-5 : 1111 1111 1111 1111 1111 1111 1111 1011
after shift : 1111 1111 1111 1111 1111 1111 1111 1110 that is -2
with shortcut : -5/4 = ???

please help ?

[ January 08, 2005: Message edited by: rathi ji ]
[ January 08, 2005: Message edited by: rathi ji ]

Jay Pawar
Ranch Hand
Posts: 411

Original post:
ex : 5>>2
5 : 0000 0000 0000 0000 0000 0000 0000 0101
after shift : 0000 0000 0000 0000 0000 0000 0000 0001 that is 1 .
with shortcut : 5/4 => ??
it seems that remainder is the output ( 5%4 = 1 )

It is not the remainder it's the quotient.
15 >> 3 = 1 ( 15 / 8 ) and not 7 which is the remainder

I am not sure if any shortcut exists for -5 >> 2.

Hope this helps ya.

ankur rathi
Ranch Hand
Posts: 3830
Thanks Jay ,

really there is no shortcut for this two :

-5 >> 2

-5 << 2

ankur rathi
Ranch Hand
Posts: 3830
Originally posted by rathi ji:
really there is no shortcut for this two :

-5 >> 2

-5 << 2

Hey it was a question not a fact ...

one more thing some day before a q was on 4 >> -23 or like that & there was very good explanation . i have used serach facility but didn't find a good answer . please if any body can help .

thanks a lot .
[ January 10, 2005: Message edited by: rathi ji ]

Rajasekar Elango
Ranch Hand
Posts: 105
Hi,

I think this should work.

For >> you to floor the value after division.

So 25 >> 3 => 25/8 => floor(3.1) => 3
-25 >> 3 => -25/8 => floor(-3.1) => -4.

Now, if right operand is -ve, you can make it positive by subtracting it from 32(for integers & 64 for long) and do above procedure..

For eg:

500 >> -25 => 500 >> 7 (32 - 25) => 3

Thanks,
Raja