Why would you ever need to shift bits?

BlitzMax Forums/BlitzMax Beginners Area/Why would you ever need to shift bits?

JoJo(Posted 2005) [#1]
What's the reasoning behind it.

Does this cause arithmetic to be performed faster or what?
All I can see is that it multiplies numbers by 2 or divide by 2 at the binary level.

I don't understand why this is ever needed.

Can someone explain?


Beaker(Posted 2005) [#2]
Some compilers will optimise an integer divide/multiply by 2 (and 4,8,16,32 etc) using a bitshift. It's not really that big an optimise these days anyway.

One common use is to combine 8-bit red, green and blue values into one 24 bit RGB number (32 bit if you include alpha). Splitting them up again is another use.

Another use is for fixed point maths - 8 bits of exponent and 24 bits of mantissa for example.

Another use: compressing data down for message sending in network applications.


MrCredo(Posted 2005) [#3]
(ARGB AND $FF000000) SHR 24

is different to

(ARGB AND $FF000000) / $1000000


ImaginaryHuman(Posted 2005) [#4]
Shifts are generally based on low-level instructions in the CPU which can very quickly move data left or right within a cpu register for various purposes. You can use it to divide and multiple by powers of two in a single instruction which is usually faster than a multiply or especially a divide which are historically very slow instructions. However, on modern hardware, powerpc, etc there is probably little to gain from that since multiply and divide are so much quicker than they used to be. But there are other uses, as mentioned above - to store more than one value in a single integer for example, to handle rgb color components, to perform quick divides and multiplies, etc.

Since there are a lot of aspects to most game engines that base sizes of things on powers of two (who knows why - it's easier), you can likely use shifting in a lot of places to divide an multiple for various purposes by those power-of-two values. E.g. tile size 32x32 is a power of 2, so doing tile x index shifted left 5 times gives you the number of pixels.

I use it to help with the storage of two short values in a single integer which happens to be retrievable and extractable faster than using two integers.