Bitwise Operations
Swap a and b around
a ^= b; b ^= a; a ^= b;
or equivalently,
a ^= b ^= a ^= b;
note: a^b obtains a mask which has 0 on bits that a and b are the same, and has 1 on bits that a and b are oppsite
Return a mask that set the first 1
c & (~c + 1) or c & -c
Return a mask that set the first 0
~c & (c + 1)
Count number of 1
int count_one1(int c) { int i; for (i = 0; c; i++) c ^= (c & -c); return i; } int count_one2(int c) { int i; for (i = 0; c; i++) c &= (c - 1); return i; } int count_one3(int c) { int n = 0, i; for (i = 0; i < 32; i++) { if (c & 1) n++; c >>= 1; } return n; }
Left rotate a byte by certain bits
char rotate(char c, int i) { i %= 8; return (c << i) | ((unsigned char)c >> (8 - i)); }
page revision: 18, last edited: 23 Apr 2012 06:48