在java中将单个十六进制字符转换为其字节值

时间:2009-07-11 18:42:26

标签: java hex

我有一个十六进制字符,比如说

char c = 'A';

将其转换为整数值的正确方法是什么

int value =??; 
assert(a == 10);

如果 a 是一个int或一个字节,那么现在真的没关系。

5 个答案:

答案 0 :(得分:17)

我不明白你为什么要转换为字符串...实际上这就是parseInt使用的:

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.

答案 1 :(得分:5)

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

答案 2 :(得分:5)

虽然发现了它。

int i = Character.digit('A',16);

答案 3 :(得分:1)

(byte)Integer.parseInt(“a”,16)

答案 4 :(得分:0)

看看Commons Codec,特别是Hex类。

http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html

您应该能够使用toDigit()方法将十六进制字符数组或字符串转换为int值:

protected static int toDigit(char ch, int index)

你需要捕获DecoderException。

try {
    int i = Hex.toDigit('C');
} catch (DecoderException de) {
    log.debug("Decoder exception ", de);
}

还有一些方法可以将char []或String转换为相应的字节数组。

相关问题