Thursday, 23 May 2019

Java: Convert byte to binary string


Using 'Integer.toBinaryString' method, you can convert a byte to binary string.

Example
byte b1 = (byte) 255;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');

App.java
package com.sample.app;

public class App {

    public static void main(String args[]) {
        byte b1 = (byte) 255;
        String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');

        byte b2 = (byte) 127;
        String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');

        System.out.println("255 in binary : " + s1);
        System.out.println("127 in binary : " + s2);

    }
}

Output
255 in binary : 11111111
127 in binary : 01111111


You may like

No comments:

Post a Comment