How to convert an integer or a long value to a byte array (and vica versa) in Java

There're a lot of ways to do this right and a lot of ways to do it wrong. Smile Here's one method that I've found to be both correct (ie. for all possible integer values the following is true: value == byteArrayToInt(intToByteArray(value))) and efficient.

Both functions work with big-endian representations of 4-byte integer values.

public static final byte[] intToByteArray(int value) {
  return new byte[] {
    (byte) (value >>> 24),
    (byte) (value >>> 16),
    (byte) (value >>> 8),
    (byte) value
  };
}

public static final int byteArrayToInt(byte[] b) {
  int value = 0;

  if (b != null) {
    if (b.length > 0) {
      value += b[0] << 24;
      if (b.length > 1) {
        value += (b[1] & 0xFF) << 16;
        if (b.length > 2) {
          value += (b[2] & 0xFF) << 8;
          if (b.length > 3) {
            value += b[3] & 0xFF;
          }
        }
      }
    }
  }

  return value;
}

Using the above examples you can easily create functions that do the same conversion for long values (ie. longToByteArray() and byteArrayToLong()).