Bit shifting

Started by
2 comments, last by bose 22 years, 9 months ago
Really simple question here... How would I divide a number by 2 using bit shifting? Probably the dumbest question you''ve ever heard but I don''t really know how bit sifting works. I mean I know it shifts the bits left or right but I am not sure of the effect and just havent had the time to sit down and thing about it lol. Maybe someone has a good way to explain the effect of bit shifting?
Advertisement
Hi.

Bit shifting is not realy hard to understand...

say we have the following Bits:

00000011 -> this would mean 3 in dec

now if you shift those bits 1 to to left you'll get
00000110 -> which is 6 in dec.

why is this so? see:
every bit has a value... if we have 8 bits the values of the bits would be:

128,64,32,16,8,4,2,1 ( i think you know that )

as you can see the value of each bit is always the double than the value of the bit on the left side of it.

now if you shift all bits 1 to the left all bits have the double value than before, and your value will be the double.

if you shift to the right all your bits will have the half value than before and your value is divided by 2.

well. i hope you understand this cos my english realy sucks...

cu

GDG
[EDIT]
ehm i had a littel error well now it should be right..
[/EDIT]

Edited by - GandalfDerGraue on July 17, 2001 6:37:28 AM
The >> operator shifts down, (divide) and the << operator shifts up (multiply)

Bit shifting works on the binary data that makes up the number. Because each bit in the number has double the value of the previous bit, shifting down one divides by two, and shifting up one multiplies by two.Take the number 738 for example. In binary this is 1011100010 (I am assuming you know how to convert from decimal to binary - if not, say so and I (or someone) will explain)

So, what happens if you bit shift this?

1011100010 >> 1 = 101110001

convert this back into decimal....

101110001 == 369

if you shift more places, say n, then the multiplier is 2^n (ie if you shift 2 places, the shift results in a multiply/divide by four)

HTH
[EDIT]

Doh. Too slow.


Edited by - Sandman on July 17, 2001 6:37:21 AM
Ah never underestimate the power of Gamedev, Thanks guys!

That halped a ton, I understand now!

This topic is closed to new replies.

Advertisement