Convert from hexadecimal integer to decimal java

173 views Asked by At

There are pre-translated numbers from hexadecimal to decimal. For example, 0x01, 0x10 and so on. I need to extract from it everything that is after x, so that I get a number that could fit as an index to the array.

The difficulty lies in the fact that the hex value is an Integer (NOT AS a String), that is, it is in this format:

int hexValue = 16; // 0x10 

And I need to get the answer 10.

Why is this necessary? I need the hexadecimal value to be a full-fledged index for the array

1

There are 1 answers

5
WJS On

Hex, binary, octal, etc are all visual presentations of a number in a specific base. Any int is already in "binary." It could be +5 (1) and ground (0) if you want to go that deep into it.

So converting an int to another base does not make sense unless it is for display purposes.

Or given a string in a particular base and converting that to an int so it can be used in mathematical expressions or data structures is also an option.

Per your comment I still believe you are somewhat confused about numeric representation. But here is how to convert a hex string to an int. This does not handle signed values.

String hexString = "2A4";
 
String hexDigits = "0123456789ABCDEF";
int result = 0;
for (char c : hexString.toCharArray()) {
     result = result * 16 + hexDigits.indexOf(c);
}
System.out.println(result);

prints

676

And let me repeat that it does not make sense to try and convert any int from one base to an int in another base, as int's are not really in any base at all. ints are treated as decimal by the compiler and we talk about them as though they are binary because it provides a common and accepted way to describe them.

Updated

You may want to check out Integer.decode. If you are reading in encoded strings with prefixes of x,X, and # for hex ,0 for octal, and a non-zero digit for decimal, you can do the following.

String [] codes = {"0x11", "021", "#11", "17"};
 
for (String code : codes) {
     System.out.println(Integer.decode(code));
}

prints

17
17
17
17