What is the radix parameter in Java, and how does

2019-01-08 23:33发布

I understand that radix for the function Integer.parseInt() is the base to convert the string into. Shouldn't 11 base 10 converted with a radix/base 16 be a B instead of 17?

The following code prints 17 according to the textbook:

public class Test {
  public static void main(String[] args) {
    System.out.println( Integer.parseInt("11", 16) );
  }
}

5条回答
\"骚年 ilove
2楼-- · 2019-01-08 23:37

To convert from base 10 to base 16 use

System.out.println(Integer.toString(11, 16));

Output will be b.

查看更多
Fickle 薄情
3楼-- · 2019-01-08 23:43

The function act backwards as you think. You convert "11" in base 16 to base 10, so the result is 17.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-08 23:50

When you perform the ParseInt operation with the radix, the 11 base 16 is parsed as 17, which is a simple value. It is then printed as radix 10.

You want:

System.out.println(Integer.toString(11, 16));

This takes the decimal value 11(not having a base at the moment, like having "eleven" watermelons(one more than the number of fingers a person has)) and prints it with radix 16, resulting in B.

When we take an int value it's stored as base 2 within the computer's physical memory (in nearly all cases) but this is irrelevant since the parse and tostring conversions work with an arbitrary radix (10 by default).

查看更多
\"骚年 ilove
5楼-- · 2019-01-08 23:55

Here,

public class Test {
      public static void main(String[] args) {
      System.out.println(Integer.parseInt("11", 16));
    }
}

11 is 16 based number and should be converted at 10 i.e decimal.

 So, integer of (11)16 = 1*16^1 +1*16^0 = 16+1 = 17
查看更多
做自己的国王
6楼-- · 2019-01-09 00:00

It's actually taking 11 in hex and converting it to decimal. So for example if you had the same code but with "A" in the string, it would output 10.

查看更多
登录 后发表回答