m0nkeymafia

Im bored so thought id post again in my C++ board Applause

Its a simple but pretty cool technique called bit shifting.
It allows you to very quickly multiply or divide integers by 2.

<>The theory:
If you dont know already integers are stored [normally] as 4 bytes within the computer, meaning you have 32 bits to play with.  On PCs they are stored in a certain way [little endian].  Basically an integer, stored as binary, may look like this:

The number 2
000000000000000000000000000010 [31 zeroes and a 2, and yes i cant count Applause]
The number 4 is exactly the same as 2, but shifted along one column
000000000000000000000000000100
The number 8 follows the same pattern
000000000000000000000000001000

So we can see we can mutiply [and indeed divide] by 2 by moving the bits in an integer up and down.  This is called shifting.

So this is how we can code using it:
int myNum = 2;
//Times by 8
myNum = myNum << 3; //Note 8 is 2^3

<>But why would you use this?
Most modern compilers will actually use this method [on compile time] if it can guaruntee you are multiplying by 2,

i.e
myNum = myNum * 2;

BUT, if you multiply by another variable x, it doesnt know it will always be a 2.
i.e.
myNum = myNum * x;

But if you know x is always a 2 you can shave off a few cycles by using bit shifting.
This really comes into its own when you are writing complex time critical code and need to shave off as much execution time as possible.  Plus its really cool and you can pull women with it Applause

perkiset

quote author=m0nkeymafia link=topic=269.msg1807#msg1807 date=1180368663

But if you know x is always a 2 you can shave off a few cycles by using bit shifting.
This really comes into its own when you are writing complex time critical code and need to shave off as much execution time as possible.  Plus its really cool and you can pull women with it Applause


Actually can be way more than a few cycles in a complex app... I've run across more than a few applications where the code was actually factored towards 2x2 mult/div everywhere possible. I doubt that the effect is as huge in a scripted language like

PHP

 , but you're right, in a compiled language it's a great technique.


Perkiset's Place Home   Politics @ Perkiset's