How to print the bits of a number in Java

2 Answers

0 votes
class Main {
    public static void main(String[] args) {
        int n = 1358;
         
        System.out.println(Integer.toBinaryString(n));
    }
}
 
 
 
/*
run:
  
10101001110
   
*/

 



answered Mar 5, 2019 by avibootz
edited Jan 29, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        int x = 153; 
          
        System.out.println(String.format("%8s", Integer.toBinaryString(x)).replaceAll(" ", "0"));
          
        System.out.println(String.format("%16s", Integer.toBinaryString(x)).replaceAll(" ", "0"));
    }
}
 
 
 
/*
run:
  
10011001
0000000010011001
   
*/

 



answered Jan 29, 2025 by avibootz
...