C examples for Operator:Bit Operator
Create a function to get n bits from position p
#include <stdio.h> unsigned getbits(unsigned x, int p, int n) { return (x >> (p + 1 - n)) & ~(~0 << n); } int bitcount(unsigned x) { int b = 0;//from ww w.j av a2 s. com for (b = 0; x != 0; x >>= 1) { if (x & 01) b++; } return b; } int main() { int n; if (bitcount(072) != 4) /* 0111010 */ printf("error 072\n"); for (int i = 1; i <= 30; i++) { if (bitcount(3 << i) != 2) printf("error 3 << %d\n", i); } for (int i = 0; i < 25; i++) { n = 033 << i; /* 011011 */ if (getbits(n, i + 3, 3) != 5) printf("error getbits 1 %d\n", i); if (getbits(n, i + 1, 2) != 3) printf("error getbits 2 %d\n", i); if (getbits(n, i + 2, 1) != 0) printf("error getbits 3 %d\n", i); } return 0; }