Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) );   } } 
like image 589
Minh Tran Avatar asked Jul 08 '13 02:07

Minh Tran


People also ask

How does Java parseInt work?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

Is radix required in parseInt?

The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.

What does this piece of code do integer parseInt string s?

Java Integer parseInt (String s) Method It returns the integer value which is represented by the argument in a decimal integer.


1 Answers

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

like image 125
nanofarad Avatar answered Sep 21 '22 05:09

nanofarad