Bit Shifting!!
Does anyone know how to add, subtract, muliply, and divide using bit shifting?
Thanks
It would be a bit (hahah pun
) difficult to add or subtract using bit shifting since bit shifting moves the bits to the left or right, which multiplies or divides the number by the base of the system, respectively. Bit sifting is base-2 in this case, so left shifting would multiply the number by two and right shifting would divide the number by two. These are really fast and are used when you would be multiplying or dividing by a number where "log in base 2 of that number is an integral value"...in other terms it''s a power of two
. Example:
Bit shifting:
The number after the shift operator is the number of places to shift. So basically y would be multiplied by 2^6, or 64.
![](smile.gif)
![](smile.gif)
x = y * 64;
Bit shifting:
x = y << 6;
The number after the shift operator is the number of places to shift. So basically y would be multiplied by 2^6, or 64.
I''m talking about shifting with carry, etc. along with AND''s, etc. which makes it possible to add, subtract, multiply, and divide. i had to do it in a class years back but couldn''t remember how i did it, i was hoping for someone to refresh my memory but i guess that isn''t looking good at the moment.
I only know about what zipster said, also I did answer your statement. Good luck with the other method, I too have read about doing it, but dont remember how too/.
bad!
thats cool, i''m not sure if it would help performance anyways, i know you answered my question, smart ass, jk. thanks for the input.
There is no point trying to add and subtract with bit shifting. Really. And to multiply by a variable, it''s faster to just use the * operator. But multiplying by a constant...
x = y * 640;
x = y * (512 + 128);
x = y << 9 + y << 7;
Just remember that a CPU''s MUL and IMUL instructions are not really that slow.
x = y * 640;
x = y * (512 + 128);
x = y << 9 + y << 7;
Just remember that a CPU''s MUL and IMUL instructions are not really that slow.
Of course, if you''re doing a LOT of multiplying by a constant (like 640), this may prove faster:
//so instead of
x = y * 640;
//you use
x = Map640[y];
//where Map640 is setup:
Map640[0] = 0;
Map640[1] = 640;
Map640[2] = 1280;
...
Map640[480] = 480 * 640;
How you populate the array is up to you...
//so instead of
x = y * 640;
//you use
x = Map640[y];
//where Map640 is setup:
Map640[0] = 0;
Map640[1] = 640;
Map640[2] = 1280;
...
Map640[480] = 480 * 640;
How you populate the array is up to you...
Dustin
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement