Saturday, April 5, 2008

Converting boolean array to int in Java

In a X509Certificate the key usage is stored as a boolean array. In order to be able to use the bitwise and & on this boolean[] it has to be converted into an int. This is how you can do this:

  int booleanArrayToInt(boolean[] a)
  {
    int result = 0;
    for (int i = 0; i < a.length; i++)
    {
      int value = (a[i] ? 1 : 0) << i;
      result = result | value;
    }

    return result;
  }
Post a Comment