Блог пользователя Adarsh_Singh_01

Автор Adarsh_Singh_01, история, 13 месяцев назад, По-английски
  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);

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

»
13 месяцев назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

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

»
13 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

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.