Bitwise operators' application

Summary Name Operator Description AND & Both bits are 1, return 1. Otherwise, return 0. OR \ One of both bit is 1, return 1. Otherwise, return 0. XOR ^ Two bits are different return 1. Otherwise, return 0. NOT ~ Flip bit, 0 becomes 1, 1 becomes 0 Shift left << Shifts all the bits to the left Right left >> Shifts all the bits to the right Application Integer Change bit //Set nth bit x |= (1 << n); //Set the right-most 0 bit to 1 x |= (x+1); //Unset nth bit x &= ~(1 << n); //Set the right-most 1 bit to 0 x &= (x-1); //Toggle nth bit x ^= (1 << n); //Get the mth bit of n (x >> n) & 1; //Swap Adjacent bits ((x & 10101010) >> 1) | ((x & 01010101) << 1); Multiplication / Division x by $2^n$ x << n //multiplication x >> n //division Round up to the next power of two x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; Round down to the next power of two x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; x = x >> 1; //the same with the code above but added this line Floor x x >> 0; 6....

January 29, 2021