In Java, we can use Integer.toBinaryString(int) to convert a byte to a binary string representative. Review the Integer.toBinaryString(int) method signature, it takes an integer as argument and returns a String.
public final class Integer extends Number
implements Comparable<Integer>, Constable, ConstantDesc {
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
//...
}
If we pass a byte into this method, Java will auto-cast / widening the byte to an int and apply sign extension. If we don’t want the sign extension, mask it (bitwise and) with a 0xff. To further understand the previous statement, please read this How to convert a byte into an unsigned byte in Java.
Byte -> Int -> Binary
This Java example will print a byte to a binary string, and pad the leading with zero.
package com.mkyong.crypto.bytes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ByteToBinary {
public static void main(String[] args) {
byte aByte = (byte) -2; // -2 (signed) and 254 (unsigned)
System.out.println("Input : " + aByte);
// byte to an unsigned integer
// & 0xff to prevent sign extension, no effect on positive
int result = aByte & 0xff;
System.out.println(result); // 254
System.out.println(Integer.toBinaryString(result)); // 1111 1110
String resultWithPadZero = String.format("%32s", Integer.toBinaryString(result))
.replace(" ", "0");
System.out.println(resultWithPadZero); // 00000000000000000000000011111110
System.out.println(printBinary(resultWithPadZero, 8, "|")); // 00000000|00000000|00000000|11111110
}
// pretty print binary with separator
public static String printBinary(String binary, int blockSize, String separator) {
// split by blockSize
List<String> result = new ArrayList<>();
int index = 0;
while (index < binary.length()) {
result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
index += blockSize;
}
return result.stream().collect(Collectors.joining(separator));
}
}
Output
Input : -2
254
11111110
00000000000000000000000011111110
00000000|00000000|00000000|11111110
For Java 8, we can use the new API to convert a byte into an unsigned int.
int result = Byte.toUnsignedInt(aByte);