Main Tutorials

Java – How to convert a byte to a binary string

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.

Integer.java

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.

ByteToBinary.java

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

Terminal

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);

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments