4 ms·
Neat :) I wrote some very slow code to set/get the Nth bit in an array of bytes. I was planning on using it for Chess bitboards - https://en.wikipedia.org/wik
by deutronium 10y ago
Neat :)
I wrote some very slow code to set/get the Nth bit in an array of bytes.
I was planning on using it for Chess bitboards - https://en.wikipedia.org/wiki/Bitboard https://en.wikipedia.org/wiki/Bitboard, but it could be used for say 8 booleans to the byte.
unsigned char getbit(unsigned char * bits,unsigned long n){
return (bits[n/8] & (unsigned char)pow(2,n%8)) >> n%8;
}
void setbit(unsigned char * bits,unsigned long n, unsigned char val){
bits[n/8] = (bits[n/8] & ~(unsigned char)pow(2,n%8)) | ((unsigned char)pow(2,n%8) * val);
}
- pjscott 10y agoYou should be able to replace the pow(2, x) part with (1 << x), so e.g. getbit() becomes return (bits[n/8] & (1 << (n%8))) >> n%8; The compiler will turn the division and modulo into shifting and masking.
- deutronium 10y agoYeah that's a good point! Don't know why I didn't think about that.