Saturday 5 April 2014

Java - convert an integer to a binary (bits/bytes) String

So! You want to convert an integer to its binary (bits and bytes) representation. There is an existing method which does this:

Integer.toBinaryString(int);

But! This will not include the leading 0s (i.e. the 0s before the most-significant 1). If you want a String with all 32 bits that make up the integer, here's an alternative method:

/**
 * @param value
 * @return the binary representation of {@code value}, including leading 0s.
 */
String toBinaryString(int value) {
  final byte[] bytes = ByteBuffer
      .allocate(4)
      .order(ByteOrder.BIG_ENDIAN)
      .putInt(value)
      .array();

  return toBinaryString(bytes);
}

/**
 * @param bytes is non-null.
 * @return the binary representation of the bytes in {@code bytes}.
 */
String toBinaryString(byte[] bytes) {
  final StringBuilder sb = new StringBuilder();

  for (int i = 0; i < bytes.length; i++) {
    sb.append(toBinaryString(bytes[i]));
    sb.append(" ");
  }

  return sb.toString();
}

/**
 * @param value
 * @return the binary representation of {@code value}.
 */
String toBinaryString(byte value) {
  final StringBuilder sb = new StringBuilder();

  for (int i = 7; i >= 0; i--) {
    boolean bitSet = (value & (1 << i)) > 0;
    sb.append(bitSet ? "1" : "0");
  }

  return sb.toString();
}