Files
notes/Puzzles/bitwise_operations.md
2021-05-14 14:20:02 +01:00

1.0 KiB

Detect if two integers have opposite signs

Արդյոք երկու ամբող թվերը նույն նշանն ունեն

bool oppositeSigns(int x, int y)
{
    return ((x ^ y) < 0);
}

Detect if integer can be devided on 8

Արդյոք ամբողջ թիվը բաժանվո՞ւմ է 8-ի

bool div8(int x)
{
    return ((x & 0x7) == 0);
}

Turn off the rightmost set bit

int fun(unsigned int n)
{
    return n & (n - 1);
}

Compute modulus division by a power-of-2-number

unsigned int getModulo(unsigned int n,
                       unsigned int d)
{
return ( n & (d - 1) );
}  

Check for Integer Overflow

bool willOverflow(int a, int b) { int result = a + b; if(a > 0 && b > 0 && result < 0) return true; if(a < 0 && b < 0 && result > 0) return true; return 0; }

Count set bits in an integer

unsigned int countSetBits(unsigned int n) { unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count; }