Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java hexadecimal to int conversion - have to remove 0X ?

I have a file with many hex numbers (for eg - 0X3B4 ). Im trying to parse this file as assign these numbers to integers, but dont seem to get Integer.parseInt to work.

   int testint = Integer.parseInt("3B4",16);  <- WORKS

   int testint = Integer.parseInt("0X3B4",16);

gives error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "0x3b4"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

What is the right way to assign the value 0XB4 to an int ?

Do I have to get rid of the 0X - its not unusual to represent hex nos this way...

like image 943
Nikhil Avatar asked Sep 27 '13 00:09

Nikhil


People also ask

What is 0x in Java?

For Hexadecimal, the 0x or 0X is to be placed in the beginning of a number. Note − Digits 10 to 15 are represented by a to f (A to F) in Hexadecimal. Here are some of the examples of hexadecimal integer literal declared and initialized as int.

How does Java handle hexadecimal?

In Java code (as in many programming languages), hexadecimal nubmers are written by placing 0x before them. For example, 0x100 means 'the hexadecimal number 100' (=256 in decimal). Decimal values of hexadecimal digits.

What are 0x and L?

The 0x is literal representation of hex numbers. And L at the end means it is a Long integer. If you just want a hex representation of the number as a string without 0x and L , you can use string formatting with %x . Or {0:x}.

How do you remove 0x from hex string in Python?

Python: hex() function For the hexadecimal representation of a float value, use the hex() method of floats. The hexadecimal representation is returned as string and starts with the prefix '0x'. To remove the prefix, use slices to return the string starting from index 2: [2:].


1 Answers

You can do

int hex = Integer.decode("0x3b4");

You are right that parseInt and parseLong will not accept 0x or 0X

like image 81
Peter Lawrey Avatar answered Oct 18 '22 20:10

Peter Lawrey