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