to Binary String - Java java.lang

Java examples for java.lang:int Binary

Description

to Binary String

Demo Code

/*//from w w  w .j  a v a2 s . c  o m
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */

public class Main{
    public static void main(String[] argv) throws Exception{
        byte value = 2;
        System.out.println(toBinaryString(value));
    }
    public static String toBinaryString(byte value) {
        String formatted = Integer.toBinaryString(value);
        if (formatted.length() > 8) {
            formatted = formatted.substring(formatted.length() - 8);
        }
        StringBuilder buf = new StringBuilder("00000000");
        buf.replace(8 - formatted.length(), 8, formatted);
        return buf.toString();
    }
    public static String toBinaryString(int value) {
        String formatted = Long.toBinaryString(value);
        StringBuilder buf = new StringBuilder(StringHelper.repeat('0', 32));
        buf.replace(64 - formatted.length(), 64, formatted);
        return buf.toString();
    }
    public static String toBinaryString(long value) {
        String formatted = Long.toBinaryString(value);
        StringBuilder buf = new StringBuilder(StringHelper.repeat('0', 64));
        buf.replace(64 - formatted.length(), 64, formatted);
        return buf.toString();
    }
}

Related Tutorials