Practical Uses for Bitwise Operators

I was very bemused at my first encounter of bitwise operations, but quickly realized that I couldn’t think of even a single use for this language feature.

My solution to the Say challenge on exercism.io represents the first occasion that I have been able to make use of this knowledge.

The challenge was to convert numbers into English words. To do this, I would need to group them into groups of three, as we normally do using comma notation, so that a number like 6,145,010 would group such as “6 million” “145 thousand” “ten”.

There are a couple different ways to do this, but I decided to pad the number so that the number of digits would always be a multiple of 3. Without a pad, I would end up getting groups like [“614”, “501”, “0”], instead of [“6”, “145”, “010”].

One possibility would be to use the remainder from a modulus division to determine the amount of pad needed. However, it is made much more concise by using the bitwise XOR operator. Here is the resulting code, and my unit tests.

const padString = function (number) {
  const pad = "0".repeat(((String(number).length-1)%3^3)-1);
  return (pad + String(number));
};

const magnitudeGroupedArray = function (number) {
  const paddedString = padString(number);
  return paddedString.match(/.{1,3}/g);
}

describe('pad', () => {
  test('pad-3', () => {
    expect(magnitudeGroupedArray(9)).toEqual(["009"]);
    expect(magnitudeGroupedArray(89)).toEqual(["089"]);
    expect(magnitudeGroupedArray(789)).toEqual(["789"]);
  });
  test('pad-6', () => {
    expect(magnitudeGroupedArray(6789)).toEqual(["006", "789"]);
    expect(magnitudeGroupedArray(56789)).toEqual(["056", "789"]);
    expect(magnitudeGroupedArray(456789)).toEqual(["456", "789"]);
  });
  test('pad-9', () => {
    expect(magnitudeGroupedArray(3456789)).toEqual(["003", "456", "789"]);
    expect(magnitudeGroupedArray(23456789)).toEqual(["023", "456", "789"]);
    expect(magnitudeGroupedArray(123456789)).toEqual(["123", "456", "789"]);
  });
});

The alternative would be much more verbose.

const padString = function (number) {
  const length = String(number).length;
  let padAmount;
  if (length % 3 == 1) padAmount = 2;
  if (length % 3 == 2) padAmount = 1;
  if (length % 3 == 0) padAmount = 0;

  const pad = "0".repeat(padAmount);
  return (pad + String(number));
};

Another perfect use for the XOR operator:

class ChessBoardCellColor {
    boolean chessBoardCellColor(String cell1, String cell2) {
        return
            (((int) cell1.charAt(0)) % 2 == 0 ^ ((int) cell1.charAt(1)) % 2 == 0)
                        ==
            (((int) cell2.charAt(0)) % 2 == 0 ^ ((int) cell2.charAt(1)) % 2 == 0);
    }
}