Java: Convert Byte to Binary String Example


We can make use of the toBinaryString() from the Integer class to convert a byte to binary String in Java.

Let us take a look at a few examples.


Example 1: Convert Single Byte to Binary String

package org.code2care.examples;

public class Example1 {

    public static void main(String[] args) {
        byte b = 101;
        String binaryString = Integer.toBinaryString(b);
        System.out.println("Byte: " + b);
        System.out.println("Binary String: " + binaryString);
    }

}
Output:

Byte: 101
Binary String: 1100101


Example 2: Convert Byte Array to Binary String

public static void main(String[] args) {

        StringBuilder binaryStringBuilder = new StringBuilder();
        byte[] byteArray = { 101, 102, 103, 127, -101, 1, 0 };

        for (byte b : byteArray) {
            binaryStringBuilder.append(Integer.toBinaryString(b & 0xFF));
        }

        System.out.println("Binary String: " + binaryStringBuilder);
    }
Output:

Binary String: 11001011100110110011111111111001101110

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap