Java教程

Java将二进制转换为十进制

我们可以使用 Integer.parseInt()方法或自定义逻辑将 二进制在Java中转换为十进制

Java二进制到十进制的转换: Integer.parseInt()

Integer.parseInt()方法使用给定的redix将字符串转换为int。 parseInt()方法的 签名如下:
public static int parseInt(String s,int redix)
让我们看看在Java中将二进制转换为十进制的简单示例。
public class BinaryToDecimalExample1{
    public static void main(String args[]){
        String binaryString="1010";
        int decimal=Integer.parseInt(binaryString,2);
        System.out.println(decimal);
    }
}
输出:
10
让我们看看Integer.parseInt()方法的另一个示例。
public class BinaryToDecimalExample2{
    public static void main(String args[]){
        System.out.println(Integer.parseInt("1010",2));
        System.out.println(Integer.parseInt("10101",2));
        System.out.println(Integer.parseInt("11111",2));
    }
}
输出:
102131

Java二进制到十进制的转换: 自定义逻辑

我们可以使用自定义逻辑将 二进制从十进制转换为Java
public class BinaryToDecimalExample3{
    public static int getDecimal(int binary){
        int decimal = 0;
        int n = 0;
        while(true){
            if(binary == 0){
                break;
            }
            else {
                int temp = binary%10;
                decimal += temp*Math.pow(2, n);
                binary = binary/10;
                n++;
            }
        }
        return decimal;
    }
    public static void main(String args[]){
        System.out.println("Decimal of 1010 is: "+getDecimal(1010));
        System.out.println("Decimal of 10101 is: "+getDecimal(10101));
        System.out.println("Decimal of 11111 is: "+getDecimal(11111));
    }
}
输出:
Decimal of 1010 is: 10Decimal of 10101 is: 21Decimal of 11111 is: 31
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4