What is the radix parameter in Java, and how does it work?

Minh Tran picture Minh Tran · Jul 8, 2013 · Viewed 47.7k times · Source

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) );
  }
}

Answer

nanofarad picture nanofarad · Jul 8, 2013

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).