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:
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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!