Saturday, August 28, 2010
Using int or long as bit array
Ever consider making use of a primitive int or long as a bit array in Java ? An int, for example, would provide a capacity of 32 bits. But how would we go about setting and testing the nth bit efficiently ?
Possible solutions:
(Don't peek if you want to give it a try!)
Possible solutions:
(Don't peek if you want to give it a try!)
Similarly for long,int setBitOn(int in, int pos) { return in | 1 << pos; }
int setBitOff(int in, int pos) { return in & (-1 ^ (1 << pos)); }
boolean isBitOn(int in, int pos) { return (in & (1 << pos)) != 0; }
boolean isBitOff(int in, int pos) { return (in & (1 << pos)) == 0; }
Any faster, better or simpler way to do this ?long setBitOn(long in, int pos) { return in | 1L << pos; }
long setBitOff(long in, int pos) { return in & (-1L ^ (1L << pos)); }
boolean isBitOn(long in, int pos) { return (in & (1L << pos)) != 0; }
boolean isBitOff(long in, int pos) { return (in & (1L << pos)) == 0; }