Bitwise Snippets

Bitwise operations are fun, but hard to remember...

Published over 3 years ago · Last edited in about 5 hours · 1 min read

...and since they're so hard, I've decided to write them here as I learn.

Know some that are missing here? Let me know on twitter

isOdd implementation

Happens that you can check if a value is odd or not by shifting it 1 bit and checking if the result is 0 or 1.

In case the result is 0, then it means the given number is an odd number.

export const isOdd = (num: number) => Boolean(num & 0x01);

isPowerOfTwo implementation

A number is a power of 2 if it has exactly one bit set in its binary representation. For example: 2 (10), 4 (100), 8 (1000), 16 (10000).

The trick: if you subtract 1 from a power of 2, all bits flip. So n & (n - 1) will be 0 if n is a power of 2 (and n > 0).

export const isPowerOfTwo = (num: number) => num > 0 && (num & (num - 1)) === 0;