Converts a byte into a String of length 8, consisting of 0s and 1s that corresponds to the binary representation of the byte - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Converts a byte into a String of length 8, consisting of 0s and 1s that corresponds to the binary representation of the byte

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte b = 2;
        System.out.println(bitStringFromByte(b));
    }/*from  www  . j a v  a  2  s.  com*/

    /**
     * Converts a byte into a String of length 8, consisting of 0s and 1s that
     * corresponds to the binary representation of the byte
     *
     * @param b byte to convert
     * @return String of 0's and 1's that is the binary representation of b
     */
    public static String bitStringFromByte(byte b) {
        String tail = Integer.toBinaryString(b & 0xFF).replace(' ', '0');
        int tailLen = tail.length();
        for (int i = 0; i < 8 - tailLen; i++) {
            tail = "0".concat(tail);
        }
        return tail;
    }
}

Related Tutorials