Java中的二进制,八进制和十六进制转换

让我们看一些在十进制,二进制,八进制和十六进制之间转换的java示例。所有示例均使用本机Java API,而不会增加任何复杂性。

使用Integer.parseInt(字符串输入,int基数)将二进制,八进制或十六进制转换为十进制

使用Integer.parseInt(String input, int radix)来自于任何类型的数转换Integer

String binaryNumber = "10101";
int decimal1 = Integer.parseInt(binaryNumber, 2);

System.out.println(binaryNumber + " in Base 10 : " + decimal1);

String octalNumber = "456";
int decimal2 = Integer.parseInt(octalNumber, 8);

System.out.println(octalNumber + " in Base 10 : " + decimal2);

String hexNumber = "ABCD";
int decimal3 = Integer.parseInt(hexNumber, 16);

System.out.println(hexNumber + " in Base 10 : " + decimal3);

Output:

10101 in Base 10 : 21
456 in Base 10 : 302
ABCD in Base 10 : 43981

使用Integer.toString(int input,int radix)从十进制转换为二进制,八进制或十六进制

用于Integer.toString(int input, int radix)将转换Integer为任何类型的基数。

Integer decimal1 = 21;
String binaryNumber = Integer.toString(decimal1, 2);

System.out.println(decimal1 + " in Base 2 : " + binaryNumber);

Integer decimal2 = 302;
String octalNumber = Integer.toString(decimal2, 8);

System.out.println(decimal2 + " in Base 8 : " + octalNumber);

Integer decimal3 = 43981;
String hexNumber = Integer.toString(decimal3, 16);

System.out.println(decimal2 + " in Base 16 : " + hexNumber);

Output:

21 in Base 2 : 10101
302 in Base 8 : 456
43981 in Base 16 : abcd

使用Integer.toXXXString(int)从十进制转换为二进制,八进制或十六进制

Integer类确实提供了许多直接使用的统一方法。在java doc中检查它们。

Integer decimal1 = 21;
System.out.println(decimal1 + " in Base 2 : " + Integer.toBinaryString(decimal1));

Integer decimal2 = 302;
System.out.println(decimal2 + " in Base 8 : " + Integer.toOctalString(decimal2));

Integer decimal3 = 43981;
System.out.println(decimal3 + " in Base 16 : " + Integer.toHexString(decimal3));

Output:

21 in Base 2 : 10101
302 in Base 8 : 456
43981 in Base 16 : abcd

saigon has written 1445 articles

Leave a Reply