Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'parseInt(String, radix)' work? [closed]

Tags:

java

parseint

I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

System.out.println(Integer.parseInt("52", 10));

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

like image 304
Annihilator Avatar asked Oct 16 '25 12:10

Annihilator


2 Answers

You're right that the number denotes the base. You are not right that

Integer.parseInt("52", 10) will give you 52 in base 10.

This will in fact parse the number 52 as if it were in base 10. 52 could be base 6 for all we know.

For example:

Integer.parseInt("101", 2);

Is saying parse the binary (base 2) number one-zero-one. It is not saying parse one hundred and one into binary. This will return the base 10 number 5.

Any number which is returned is a standard integer which if you try to print it will be in base 10.


Worth noting that if you try and parse a number which can not possibly exist in that base, for example:

Integer.parseInt("599", 2);

then you will get an exception.

like image 55
Michael Avatar answered Oct 18 '25 14:10

Michael


The string you are parsing could be in a specific base which you supply with the radix command to parse to an int. The int is a numerical value and doesn't have a specific base per se.

Examples

Integer.parseInt("52", 10) returns 52
Integer.parseInt("52", 8) returns the numerical value 42 (8*5+2)
Integer.parseInt("A2", 16) returns the base 10 value 162
like image 23
Tyler Avatar answered Oct 18 '25 14:10

Tyler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!