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

6

29

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) );
  }
}
Doubletree answered 8/7, 2013 at 2:0 Comment(2)
The other way round. You're asking it to interpret "11" in base-16. i.e. 1*16 + 1.Colorless
@MinhTran Please checkmark the answer that helped you most.Split
S
18

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

Split answered 8/7, 2013 at 2:3 Comment(0)
T
6

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.

Trice answered 8/7, 2013 at 2:3 Comment(0)
B
6

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
Blindage answered 7/12, 2014 at 18:53 Comment(0)
D
5

you basically telling to parse 11 as if it was base 16 so if you know how to convert from hex to decimal it will look like this 11 in hex = ((16^0 ) * 1) + ((16^1) * 1) = 17 in decimal

if you want to convert from base 10 to any base use:

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
Darrelldarrelle answered 1/9, 2020 at 17:55 Comment(1)
This must be answer, voted up.Houseless
O
1

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

Overexert answered 8/7, 2013 at 2:5 Comment(0)
C
1

To convert from base 10 to base 16 use

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

Output will be b.

Chambers answered 25/11, 2015 at 4:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.