In the post-apocalyptic world of Logan’s Run, humans live out cramped lives in a bunker. Because of the crowded conditions, all citizens must submit to Carnival on their 30th birthdays. What do you do on your Carnival day? You and all the other 30 year olds spiral up into the air and get zapped to death.
Sound like a bad deal? It gets worse. The radiation outside has long since subsided, and the rules being enforced are no longer necessary.
Who Needs Bits?
When I started programming (on 8-bit processors), I mostly worked with integers. When floating point numbers became available, I avoided them for years because they were slow. We did as much math as we could with integers and bit operations. Shift left once, and that’s a multiplication by 2. If you wanted to multiply by 10, you’d do a shift left by one (times two) and a shift left by 3 (times eight) and add those results together.
Here’s what I found out. Just about everything I tried was faster with bitwise operations than with other solutions (even in Internet Explorer). No, you can’t usefully replace one multiplication with a series of adds and shifts, but by no means are bitwise operators too slow to be useful.
k=~~i; //this is much faster k=Math.floor(i); //than this
You can lop off the decimal part of a number not just with ~~, but with ^0 and <<0, too. And they are ALL significantly faster, in all modern major browsers, than calling Math.floor().
//break a number in the range 0-65535 into // low and high bytes // this is significantly faster lo = i & 255; hi = i >> 8; //than this lo = i % 256; hi = (i-lo)/256;
- Don’t mistake bitwise for logical operators.
- Learn the difference between “-” and “~”.
- Remember that >> shifts the sign bit down while >>> shifts a zero into the top bit.
When should you be using bitwise operators? Obviously, when you want to pack a bunch of flags into one variable. That should be much faster than having an array of flags.
Dealing with the red, blue, and green parts of a color call out for bitwise operators.
And think about using a shift when you want to multiply or divide by a power of 2, while at the same time converting a floating point number into an integer. Two operations for the price of one!