Using JavaScript-bitwise AND and -bitwise NOT for setting a number to 0

Posted on


Obviously is the XOR-operator is used in low-level programming-languages used a lot for setting a value back to all bits 0.

For example:

11010 ^ 11010 => 00000

Brought my teacher to figuring a out few exercises.

One is:
“Set the bits of a number back to 0 by using just the bitwise AND (&) and the bitwise NOT (~) operators.”

I’ve got now this solution:

let readline = require('readline-sync');

const limit = 100;


function setNumberToNull(num) {
  // First invert the bits of the number.
  // Then compare every bit with the not
  // inverted number using an bitwise and.
  return num & (~num);

// ########################################

function testSetNumberToNull(limit) {
  let i;

  for (i = 0; i < limit; i++) {
    let testNum = Math.floor(Math.random() * 10000);
    let tmp = setNumberToNull(testNum);

    if (tmp) {
      return { test : i, message : testNum + ' caused failure.' };

  return { test : i, message : 'All tests passed.'};


I works fine. Nevertheless I would appreciate your review.


Well, yes, num & (~num) does result in zero. Not much to review there. Seems you’ve solved the task you were given.

Of course, one might as well return/assign a literal zero, and skip two bitwise operations.

There’s one JavaScript-specific caveat to all of this though: JavaScript’s bitwise operations only work on 32-bit integers. However, that’s not a datatype that usually exists in JavaScript: Numbers in JavaScript are all IEEE 756 64-bit floats.

The moment you use a bitwise operator on them, however, they are converted (with potential loss) to 32-bit ints, and the result then represented as a float again.

Of course, that’s all academic, since whatever int representation you get, a & (~a) will result in zero.

But other bitwise operations can give strange results. For instance, OR’ing with zero should just return the number unaltered, but if the number’s too large, its most-significant bit will end up being interpreted as the sign bit as the internal 32-bit conversion is always signed. So you get things like this:

2147483647 | 0 // => 2147483647
2147483648 | 0 // => -2147483648

The second number is large enough to flip the high bit, and thus it’s interpreted as negative.

Anyway, point is: Yes, a & (~a) will result in zero, for any value of a, despite JS’s internal strangeness, because whatever it converts the input to, it also negates. But it’s a special case; in other contexts bitwise operations in JS may be treacherous.

Leave a Reply

Your email address will not be published. Required fields are marked *