Some Tricks for Bit Manipulation

Revision en1, by Adarsh_Singh_01, 2025-03-27 21:54:18
  1. Checking Odd/Even

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

  2. Clearing the Lowest Set Bit

    x = x & (x — 1);

  1. Extracting the Lowest Set Bit

    int lowest = x & -x;

  1. Counting Set Bits (Brian Kernighan’s Algorithm)

int count = 0; while (x) { x &= (x — 1);// clear the lowest set bit count++; }

  1. XOR Swap Trick

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

  1. Converting Case for Letters

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

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

  1. 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++;

  1. 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)

  1. Averaging Two Numbers Without Overflow

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

Tags bit manipulation

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Adarsh_Singh_01 2025-03-27 21:54:18 1243 This blog is necessary for my college....Ignore if you don't find it helpful (published)