I have a single hexadecimal character, say
char c = 'A';
What's the proper way of converting that to its integer value
int value =??;
assert(a == 10);
Doesn't matter really for now if a is an int or a byte.
I have a single hexadecimal character, say
char c = 'A';
What's the proper way of converting that to its integer value
int value =??;
assert(a == 10);
Doesn't matter really for now if a is an int or a byte.
Take a look at Commons Codec and in particular the Hex class.
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
You should be able to convert a hex char array or string to an int value using the toDigit() method:
protected static int toDigit(char ch, int index)
You'll need to catch DecoderException though.
try {
int i = Hex.toDigit('C');
} catch (DecoderException de) {
log.debug("Decoder exception ", de);
}
There's also methods there to convert a char[] or String to the corresponding byte array as well.
int value;
try {
value = Integer.parseInt(Character.toString(c), 16);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a hex char");
}
i don't see why you should have to convert to string... in fact this is what parseInt uses:
public static int digit(char ch, int radix)
int hv = Character.digit(c,16);
if(hv<0)
//do something else because it's not hex then.