How to convert an integer to binary with leading zeros in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int a = 7;
        
        System.out.println(String.format("%4s", Integer.toBinaryString(a)).replace(' ', '0'));
        
        System.out.println(String.format("%8s", Integer.toBinaryString(56)).replace(' ', '0'));
    }
}



/*
run:
 
0111
00111000
 
*/

 



answered Dec 26, 2021 by avibootz
...