将二进制数转换为十进制数
二进制数是仅由 2 个数字组成的数字:
0
和
1
。它们可以用基本的
2
数字系统表示。例如,
10 (2), 1000 (8), 11001 (25)
十进制数是由 10 个数字组成的数字:
0
、
1
、
2
、
3
、
4
、
5
、
6
、
7
、
8
、
9
。它们可以用基本的
10
数字系统表示。
18, 222, 987
在这里,我们将编写一个 Java 程序,使用内置方法和自定义方法将二进制数转换为十进制数,反之亦然。
示例 1: 使用自定义方法将二进制转换为十进制
class Main { public static void main(String[] args) { // binary number long num = 110110111; // call method by passing the binary number int decimal = convertBinaryToDecimal(num); System.out.println("Binary to Decimal"); System.out.println(num + " = " + decimal); } public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) { remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
输出
110110111 in binary = 439 in decimal
以上程序的工作原理如下:
<人物>

示例 2: 使用 parseInt() 将二进制转换为十进制
class Main { public static void main(String[] args) { // binary number String binary = "01011011"; // convert to decimal int decimal = Integer.parseInt(binary, 2); System.out.println(binary + " in binary = " + decimal + " in decimal."); } }
输出
01011011 in binary = 91 in decimal.
这里,我们使用了
Integer
类的
parseInt()
方法将二进制数转换为十进制数。
示例 3: 使用自定义方法将十进制转换为二进制
class Main { public static void main(String[] args) { // decimal number int num = 19; System.out.println("Decimal to Binary"); // call method to convert to binary long binary = convertDecimalToBinary(num); System.out.println("\n" + num + " = " + binary); } public static long convertDecimalToBinary(int n) { long binaryNumber = 0; int remainder, i = 1, step = 1; while (n!=0) { remainder = n % 2; System.out.println("Step " + step++ + ": " + n + "/2"); System.out.println("Quotient = " + n/2 + ", Remainder = " + remainder); n /= 2; binaryNumber += remainder * i; i *= 10; } return binaryNumber; } }
输出
Decimal to Binary Step 1: 19/2 Quotient = 9, Remainder = 1 Step 2: 9/2 Quotient = 4, Remainder = 1 Step 3: 4/2 Quotient = 2, Remainder = 0 Step 4: 2/2 Quotient = 1, Remainder = 0 Step 5: 1/2 Quotient = 0, Remainder = 1 19 = 10011
以下是该程序的工作原理:
示例 4: 使用 toBinaryString() 将十进制转换为二进制
我们也可以使用
Integer
类的
toBinaryString()
方法将十进制数转换为二进制数。
class Main { public static void main(String[] args) { // decimal number int decimal = 91; // convert decimal to binary String binary = Integer.toBinaryString(decimal); System.out.println(decimal + " in decimal = " + binary + " in binary."); } }
输出
91 in decimal = 1011011 in binary.
此处,
人物>
toBinaryString()
方法接受一个整数参数并返回以 2 为底的数字(二进制)的字符串表示形式。