Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

8,512 questions

11,796 answers

573 users

How to convert converts a base 10 integer to base 2 String in Java

2 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        for (int i = -3; i < 11; i++) 
               System.out.println(i + ": " + toBinary(i));
    }

    public static String toBinary(int n) {
        boolean negative = n < 0;
        n = Math.abs(n);        
        String binary = "";

        while(n > 1) {
            binary = (n % 2) + binary;
            n /= 2;
        }
        binary = n + binary;
        if (negative)
            binary = "-" + binary;
        
        return binary;
    }
}
    
/*
run:
   
-3: -11
-2: -10
-1: -1
0: 0
1: 1
2: 10
3: 11
4: 100
5: 101
6: 110
7: 111
8: 1000
9: 1001
10: 1010
    
*/

 




answered Jun 28, 2017 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        for (int i = -3; i < 11; i++) 
              System.out.println(i + ": " + Integer.toBinaryString(i));
    }
}
    
/*
run:
   
-3: 11111111111111111111111111111101
-2: 11111111111111111111111111111110
-1: 11111111111111111111111111111111
0: 0
1: 1
2: 10
3: 11
4: 100
5: 101
6: 110
7: 111
8: 1000
9: 1001
10: 1010
    
*/

 




answered Jun 28, 2017 by avibootz
...