views:

1413

answers:

5

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.

A: 

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.

Jon
+4  A: 
int value;
try {
    value = Integer.parseInt(Character.toString(c), 16);
}
catch (NumberFormatException e) {
    throw new IllegalArgumentException("Not a hex char");
}
jqno
A: 

(byte)Integer.parseInt("a", 16)

Nat
+6  A: 

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.
Victor
+3  A: 

Found it myself though.

int i = Character.digit('A',16);
nos
Nice - didn't know about that.
Jon Skeet