How to convert decimal to binary in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int decimal = 23;
         
        String binary = Integer.toBinaryString(decimal);
         
        System.out.println(binary);
    }
}
  
  
  
  
/*
run:
   
10111
   
*/

 



answered Jan 12, 2022 by avibootz
edited May 11, 2024 by avibootz
0 votes
public class MyClass {
    public static int[] convert_decimal_to_binary(int decimal, int[] binary) {
        int i = 0;
        
        while (decimal > 0) {    
            binary[i++] = decimal % 2;    
            decimal = decimal / 2;    
        }   
        
        return binary;
    }
    
    public static void main(String args[]) {
        int decimal = 23;
        int binary[] = new int[8];    

        binary = convert_decimal_to_binary(decimal, binary);
        
        for (int i = binary.length - 1; i >= 0; i--) {    
            System.out.print(binary[i]);    
        }    
    }
}
 
 
 
 
/*
run:
  
00010111
  
*/

 

 



answered Jul 19, 2022 by avibootz
edited May 11, 2024 by avibootz

Related questions

1 answer 184 views
1 answer 174 views
3 answers 357 views
2 answers 203 views
2 answers 216 views
...