/****** * bit_ops.c * * sample bit operations in C * * In all this I'm passing in characters explicitly, and returning characters * where appropriate so that these routines have no side effects. If you'd * rather directly on a bit in a larger buffer, make the inputs pointers * (i.e. "char* c") instead. * $ make bit_ops * gcc -march=athlon64 -O2 bit_ops.c -o bit_ops * $ ./bit_ops * 'a' is ascii '97' ('141' octal) which has '3' 1's in binary. * 'a' base 2 is '01100001' * flipped bit 3 : 01101001 * flipped bit 3 again : 01100001 * set bit 2 to 1 : 01100101 * set bit 2 to 1 again : 01100101 * set bit 2 to 0 : 01100001 * set bit 2 to 0 again : 01100001 * * Jim M, April 4 2007 *******/ #include typedef int bool; // declare boolean type (for convenience) // Return the number of 1's in the binary representation of c. int bitcount(char c){ int count; for (count=0; c != 0; c>>=1){ if (c & 1){ count++; } } return count; } // Return true (i.e. 1) if the n'th bit (0 is rightmost) of c is 1. bool bittest(char c, int n){ return ((1<=0; i--){ printf("%1i", bittest(c,i)); } } // ------------------------------------------------------- int main(){ char a = 'a'; printf(" '%c' is ascii '%i' ('%o' octal) which has '%i' 1's in binary. \n", a, (int)a, (int)a, bitcount(a)); printf(" '%c' base 2 is '", a); print_base2(a); printf("'\n"); a = bitflip(a, 3); printf(" flipped bit 3 : "); print_base2(a); printf("\n"); a = bitflip(a, 3); printf(" flipped bit 3 again : "); print_base2(a); printf("\n"); a = bitset(a, 2, 1); printf(" set bit 2 to 1 : "); print_base2(a); printf("\n"); a = bitset(a, 2, 1); printf(" set bit 2 to 1 again : "); print_base2(a); printf("\n"); a = bitset(a, 2, 0); printf(" set bit 2 to 0 : "); print_base2(a); printf("\n"); a = bitset(a, 2, 0); printf(" set bit 2 to 0 again : "); print_base2(a); printf("\n"); }