Wednesday, January 25, 2023

The Math.Power of Bit Masks

 This article was originally published on JRoller on the 9/9/2011

Quite often, you would see lines like these in a program, for defining some bit masks:

  public static final int BIT_ZERO_MASK = 1;
  public static final int BIT_ONE_MASK = 2;
  public static final int BIT_TWO_MASK = 4;
  ...
  public static final int BIT_TWENTY_ONE_MASK = 2097152;

Don't pay too much attention to the constants name, imagine something more meaningful here. The point is, when the mask is encompassing more and more bits, you end up with cryptic numbers, like this 2097152 at the end. Often, the developer would add a comment, like this:

  public static final int BIT_TWENTY_ONE_MASK = 2097152; //2^21

Recently (and that's the reason for my post), I spotted this attempt at giving a meaning to these numbers:

  public static final int BIT_ZERO_MASK = Math.pow(2, 0);
  public static final int BIT_ONE_MASK = Math.pow(2, 1);
  public static final int BIT_TWO_MASK = Math.pow(2, 2);
  ...
  public static final int BIT_TWENTY_ONE_MASK = Math.pow(2, 21);

Although mathematically correct, it seemed to me a bit overkill for the low order bits. Also, using a general mathematical method for bit calculation shows that the developer has not much idea about the existing bit operations existing natively in Java. So if you really want to give a meaning to those numbers, so the next developer would understand, I suggest rather using a bit shifting operation, like this:

  public static final int BIT_TWENTY_ONE_MASK = 1 << 21;

And if you are one of those lucky guys who can already use Java 7 at work, there is this even nicer solution:
  public static final int BIT_ZERO_MASK = 0b000_0001;
  public static final int BIT_ONE_MASK = 0b000_0010;
  public static final int BIT_TWO_MASK = 0b000_0100;
  ...
  public static final int BIT_TWENTY_ONE_MASK = 0b00010000_00000000_00000000;

Nowadays, Java 7 syntax is hopefully supported everywhere...

No comments:

Post a Comment