DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Dec 2003
Location
London
Posts
10

Bit-wise shifting

Hello,

I am trying to understand bit-wise shiting.

If I have 54 << 3 I know that 54 is represented in binary as 110110

How do I carry on to get to the final answer ?

Imanuel.

2. Registered User
Join Date
Feb 2004
Posts
3
Hi Imanuel,
The example that you show shift the bit pattern three places to the left inserting zeroes on the new positions, so 54 << 3, will become 110110000 binary which equals decimal 432.

In general, each bit-shift to the left multiplies by 2, so here 54 is multiplied by 2*2*2=2^3, and, generally,
n << m = n*2^m
But beware of the number of available bits (normally 32).

Shifting to the right removes bits from the right, so 54 >> 3 would become 110 binary which is decimal 6. - Each bit-shift to the right divides by 2 and rounds (towards 0) to the closest integer.

Best regards,
Nielsen

3. Senior Member
Join Date
Dec 2003
Posts
3,366
Also, some compilers do funny things with the sign bit. Visual studio shifts everything as a unsigned (all the bits shift) but I have seen compilers shift an integer and leave the sign bit alone, for example

10001 << 1
10010 (some compilers)
00010 (visual)

4. I recently wrote an article about bitwise operators. It will shed some light on this topic:

http://www.devx.com/getHelpOn/10MinuteSolution/18019

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts

 FAQ Latest Articles Java .NET XML Database Enterprise