• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Bitwise operators: Bit shift and OR

G'day all,

I've just started dipping my toes into the world of bitwise operators. After reading the manual and looking at some old blog articles by Mike as well as other tutorials, I was wondering what the differences are between bitshifting (1 << 2) and OR ( | ) for setting a bit.

I've seen both ways utilised although bit shifting seems to be the most commonly used. Anyone care to explain why this would be the preferred method?
 

Mike

nobody important
GMC Elder
Nothing really.

bit shifting constants (1<<2) and oring the result, (i.e. "a = (1<<2) | a" will compile to "a = 4 | a" anyway.
but bit shifting is sometimes easier to allocate "bits" for flags etc - especially using enums. But it all boils down to the same thing really.

Shifting comes into it's own for integer multiplication and dividing. "a = a>>4" will divide by 16 and floor it at the same time for example, which is obviously quicker. Similarly, ANDing with a bitmask can be the equivalent of dividing, flooring and scaling back up..

"a = a & $FFFFFFF0"

would be

a = (floor(a/16))*16

again, obviously faster...
 

NightFrost

Member
Things mentioned above come up frequently when you're dealing with representing anything grid-like on display. Imagine a displaying a grid with 16x16 pixels cells. You can click with mouse anywhere but instances the click spawns need to spawn aligned to the grid. That's when
"a = a & $FFFFFFF0"
would be
a = (floor(a/16))*16
will give you the exact coordinates you need. Similarly, using the bitwise division on coordinates
would give you the correct coordinates in grid space.
 

TheouAegis

Member
I'm comfortable with ORing, but I use 1<< when in for loops or whatnot.

for(i=0; i<16; i++) arr[ i ] = 1<<i;

Or use power.

for(i=0; i<16; i++) arr[ i ] = power(2,i);

Or is it pow in GM? Whatever.
 
Top