Convert integer to Binary String by length - Java java.lang

Java examples for java.lang:int Binary

Description

Convert integer to Binary String by length

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int i = 2;
        int length = 2;
        System.out.println(toBinaryString(i, length));
    }/*from  ww w .ja  v a2s .c  om*/

    public static String toBinaryString(int i, int length) {
        String binary = Integer.toBinaryString(i);
        int len = binary.length();
        while (len < length) {
            binary = "0" + binary;
            len++;
        }

        return binary;
    }
}

Related Tutorials