of crazy inefficient for loop. Here's a way that I figured out how to do that (not to say I invented it or anything, but I couldn't find it when I searched for it).
Obviously this has compiler and machine dependencies, and probably doesn't work on the Ides of March, so use at your own risk.
In this example, I want to generate 6 bits of 1's (so 0b111111):
#include <stdio.h>
main(){
unsigned short a;
short b;
int n = 6;
b = 1 << n;
a = (unsigned short) -b; // extend the left bits
printf("a is %hx\n", a);
printf("~a is %hx\n", ~a);
a = ~a; // now b should be 0b111111
}
That's probably like 4 or 5 operations, so for 6 bits it probably sucks. But if you use 64 bit long longs and want to generate 47 one's then it will save some cycles.
Isn't playing with bits fun?
No comments:
Post a Comment