drrob drrob - 2 months ago 12
Java Question

Parse a C-style programmer's integer in Java

This is one is short, but I can't find the answer anywhere.

Is there a jdk routine that can parse a string to an int, and autodetect and convert C-style programming conventions:


  • 123 (decimal)

  • 0x1ABC (hex)

  • 0x1abc (hex)

  • 0777 (octal)



Thanks!

EDIT: Let me be clear here, I know I can handroll this method. I already did so! I know what a radix is and about Integer.parse(..., radix)! What I am asking is, hasn't the JDK already got a method that handles all the cases. A one-liner for the whole lot...

Answer

I can't remember such function in standard JDK.

If you want to auto detect style, you cat write helper function with switch-case or Strategy pattern.

First, check if number string starts with 0x, if no - check if it starts with 0 at all. But this won't work if you will have binary number. But there are no such in your question ^_^.

See Integer.parse(String s, radix) method.