Bits > Bytes
Posted by broseApr 30
Here’s a tip to improve the speed and efficiency of your C programs: BIT OPERATIONS ARE MUCH FASTER THAN BYTE OPERATIONS!!! Let’s say you want to multiply a variable by 2 in your C program. Well, you could do:
variable = variable * 2;
But let’s consider that in order to perform this operation, the system will need to deal with at least two pieces of data: the variable, and the constant 2. It would be nice if there were a way to perform some of these basic math operations without having to deal with multiple data points. Alas, there is:
variable << 1; This simply shifts the bits one to the left. Why does this work? Let's say: 00000100 = 4 Shifting the bits one to the left yields: 00001000 = 8 This is simply an underlying principle of the binary system that computers use. This tip also works in reverse - you don't need to ever divide by two, either! You can just bitshift one to the right! Now, I don't have any empirical evidence at the moment to support this claim numerically, but it's true, the bitshift operations will always run much faster than the numerical operation. The proof is simply logical. Now here's the nugget of the day, as found on an interwebs forum, allegedly from the original K&R C book. It's a simple function to determine if a number is a power of two: if(!(phys_mem_size & (phys_mem_size - 1))) { printf("This number is a power of two."); } How's it work? Consider that a power of two will only have one bit set. It follows, therefore, that subtracting one from it will set that bit to zero, and every bit after it equal to one. Taking the binary and of these values results in something like: 16 = 00010000 15 = 00001111 & = 00000000 The important thing is to reverse the statement, that is, if NOT this and that, since if it is a power of two, a zero will be returned, which is false in C. There's plenty of other operations that can be done in C that can take advantage of the bit-patterns and power-of-two-nature of computers. Such ops can be performed on the mantissa of floats sometimes to produce interesting results that are mathematically correct. Do yourself and your computer a favour - think of this sort of low-level trickery first when trying to solve a problem while programming, it'll help you produce cleaner, faster, and more efficient code, not to mention making it look more professional.
No comments