Format int To Bin String - Java java.lang

Java examples for java.lang:int Binary

Description

Format int To Bin String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int val = 2;
        int width = 2;
        System.out.println(intToBinString(val, width));
    }/*from w w w.j  ava2s  .c o m*/

    static String mZeroes = "00000000000000000000000000000000";

    public static String intToBinString(int val, int width) {
        String str = Integer.toBinaryString(val);
        if (str.length() >= width) {
            return str;
        }
        return mZeroes.substring(0, width - str.length()) + str;
    }
}

Related Tutorials