Hamsar's blog

By Hamsar, history, 10 hours ago, In English

Checking Odd/Even

if (x & 1) { // x is odd } else { // x is even }

Clearing the Lowest Set Bit

x = x & (x — 1);

Extracting the Lowest Set Bit

int lowest = x & -x;

Counting Set Bits (Brian Kernighan’s Algorithm) int count = 0; while (x) { x &= (x — 1);// clear the lowest set bit count++; }

XOR Swap Trick

a ^= b; b ^= a; a ^= b;

Converting Case for Letters

->Uppercase to Lowercase: char lower = ch | ' ' ;

->Lowercase to Uppercase: char upper = ch & '_' ;

Next Highest Power of 2

unsigned int v = original; v--;// in case v is already a power of 2 v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16;// For 32-bit integers; extend for 64-bit as needed. v++;

Multiply or Divide by Powers of Two int mul = x << 3; // Multiply x by 8 (2^3) int div = x >> 2; // Divide x by 4 (2^2)

Averaging Two Numbers Without Overflow

int average = (x & y) + ((x ^ y) >> 1);

  • Vote: I like it
  • 0
  • Vote: I do not like it