Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to convert binary number to decimal in Java

3 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "10101011"; 
        
        int dec = Integer.parseInt(s, 2); 

        System.out.println(dec);
    }
}



/*
run:

171

*/

 



answered May 9, 2019 by avibootz
edited May 9, 2024 by avibootz
0 votes
public class MyClass {
    public static int binary_to_decimal(String s) { 
        int dec = 0;
 
        for (int i = s.length() - 1, j = 0; i >= 0; i--, j++) { 
            if (s.charAt(i) == '1') {
                dec += Math.pow(2, j); 
            }
        } 

        return dec; 
    } 

    public static void main(String args[]) {
        String s = "10101011"; 
        
        int dec = binary_to_decimal(s); 

        System.out.println(dec);
    }
}



/*
run:

171

*/

 



answered May 9, 2019 by avibootz
edited May 9, 2024 by avibootz
0 votes
public class MyClass {
    public static long binary_to_decimal(long binaryNumber) { 
        long decimalNumber = 0;
        int i = 1, reminder = 0;
   
        while (binaryNumber != 0) {
            reminder = (int)binaryNumber % 10;
            decimalNumber += reminder * i;
            i = i * 2;
            binaryNumber = binaryNumber / 10;
        }

        return decimalNumber; 
    } 
 
    public static void main(String args[]) {
        long binaryNumber = 10011;
         
        long dec = binary_to_decimal(binaryNumber); 
 
        System.out.println(dec);
    }
}
 
 
 
/*
run:
 
19
 
*/

 



answered May 9, 2024 by avibootz

Related questions

1 answer 145 views
2 answers 176 views
2 answers 233 views
233 views asked Jan 12, 2022 by avibootz
1 answer 158 views
2 answers 138 views
...