Understanding Bitwise Operations in Javascript

const isOdd(num) {
return !!(num & 1);
}

From the beginning

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024 + 2048 + 4096 + 8192 + (8192 * 2) + (8192 * 4) + (8192 * 8) + (8192 * 16) + (8192 * 32) + (8192 * 64) + (8192 * 128) + (8192 * 256) + (8192 * 512) + (8192 * 1024) + (8192 * 2048) + (8192 * 4096) + (8192 * 8192) + ((8192 * 8192) * 2) + ((8192 * 8192) * 4) + ((8192 * 8192) * 8) + ((8192 * 8192) * 16)

Each bitwise operator

Bitwise AND: &

Bitwise OR: |

Bitwise XOR: ^

Bitwise NOT: ~

/**
* @param {number} n
*/
decimal_to_binary = function(n) {
if (n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return n.toString(2);
}

Zero Fill Bitwise Left Shift: <<

Zero Fill Bitwise Right Shift: >>>

Sign Preserving Bitwise Right Shift: >>

Examples

/*
* @param {number} decimal
* @returns {string}
*/
function decimal2binary(decimal){
return (decimal >>> 0).toString(2);
}
(-1 >>> 0) === 0xFFFFFFFF

A more real example

function subsets(array) {
const result = [];
result.push([]);

for (let i = 1; i < (1 << array.length); i++) {
const subset = [];
for (let j = 0; j < array.length; j++) {
if (i & (1 << j)) {
subset.push(array[j]);
}
}
result.push(subset);
}

return result;
}
Math.pow(2, array.length)
i & (1 << j)
[
[], [ 1 ], [],
[ 1 ], [], [ 1 ],
[], [ 1 ]
]
[
[], [ 1 ],
[ 2 ], [ 1, 2 ],
[], [ 1 ],
[ 2 ], [ 1, 2 ]
]
[
[], [ 1 ],
[ 2 ], [ 1, 2 ],
[ 3 ], [ 1, 3 ],
[ 2, 3 ], [ 1, 2, 3 ]
]

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store