我知道函数Integer.parseInt()
的基数是将字符串转换为的基础。用基数/基数 16 转换的 11 base 10 不应该是 aB
而不是17
?
以下代码根据教科书打印17:
public class Test {
public static void main(String[] args) {
System.out.println( Integer.parseInt("11", 16) );
}
}
当您ParseInt
使用基数执行操作时,11 基数 16 被解析为 17,这是一个简单的值。然后打印为基数 10。
你要:
System.out.println(Integer.toString(11, 16));
这采用十进制值 11(目前没有基数,例如有“11 个”西瓜(比一个人的手指数多一个))并以基数 16 打印,结果为B
.
当我们取一个int
值时,它以 2 为底存储在计算机的物理内存中(几乎在所有情况下),但这无关紧要,因为 parse 和 tostring 转换使用任意基数(默认为 10)。
它实际上是采用11
十六进制并将其转换为十进制。因此,例如,如果您有相同的代码但"A"
在字符串中,它将输出10
.
这里,
public class Test {
public static void main(String[] args) {
System.out.println(Integer.parseInt("11", 16));
}
}
11是基于16的数字,应转换为 10,即十进制。
So, integer of (11)16 = 1*16^1 +1*16^0 = 16+1 = 17
你基本上告诉解析 11 就好像它是基数 16 所以如果你知道如何从十六进制转换为十进制它会看起来像 11 in hex = ((16^0 ) * 1) + ((16^1) * 1 ) = 17 十进制
如果您想从 base 10 转换为任何基本用途:
Integer.toString(11, 16); //HEXA
output: b
Integer.toString(11, 10); //decimal
output: 11
Integer.toString(11, 8); //octal
output: 13
Integer.toString(11, 2); //Binary
output: 1011
该功能按您的想法倒退。您将基数为 16 的“11”转换为基数 10,因此结果为 17。
要将基数 10 转换为基数 16,请使用
System.out.println(Integer.toString(11, 16));
输出将是 b。