Adarsh_Singh_01's blog

By Adarsh_Singh_01, history, 13 months ago, In English
  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);

  • Vote: I like it
  • +4
  • Vote: I do not like it

| Write comment?
»
13 months ago, hide # |
 
Vote: I like it +1 Vote: I do not like it

x + y = x ^ y + (x & y) << 1. Probably not very useful but a fun-fact nontheless.

»
13 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

This one is also very cool:

bool power_of_2 = (x > 0) && !(x & (x - 1));

It checks whether the number is an power of 2 or not.