CodeGym /Java 博客 /随机的 /Java将二进制转换为十进制
John Squirrels

San Francisco

Java将二进制转换为十进制

1. 使用 Java 方法
2. 使用自定义逻辑

Java 预建方法

Java 为我们提供了Integer.parseInt()方法来将字符串转换为整数。parseInt()方法属于Integer类。

句法

``````
public static int parseInt(String binaryNumber, int radix)
``````

例子

``````
public class ConvertingBinaryToDecimal {
public static void main(String args[]){
String binaryNumber="10101";
int decimalNumber=Integer.parseInt(binaryNumber,2);
System.out.println(decimalNumber);
}
}
``````

21

使用自定义逻辑

例子

``````
public class ConvertingBinaryToDecimal {
// function for converting binary to decimal number
public static int getDecimalNumber(int binaryNumber){
int decimalNumber = 0;
int power = 0;
while(binaryNumber > 0){
//taking the rightmost digit from binaryNumber
int temp = binaryNumber%10;
//now multiplying the digit and adding it to decimalNumber variable
decimalNumber += temp*Math.pow(2, power);
//removing the rightmost digit from binaryNumber variable
binaryNumber = binaryNumber/10;
//incrementing the power variable by 1 to be used as power for 2
power++;
}
return decimalNumber;
}

public static void main(String args[]){
System.out.println("Decimal value is: "+getDecimalNumber(111010));
System.out.println("Decimal value is: "+getDecimalNumber(001010));
}
}
``````

结论

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION