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

5

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

char c = 'A';

什么是将它转换为整数值的正确方式?
int value =??; 
assert(a == 10);

目前来看,a 是 int 类型还是 byte 类型并不重要。

5个回答

18

我不明白为什么你需要把它转换成字符串... 实际上这就是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.

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

5

虽然我是自己找到的。

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

1

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

的意思是将十六进制字符串 "a" 转换为整数,再将其转换为字节类型。

0

看一下Commons Codec,特别是Hex类。

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

你应该能够使用toDigit()方法将十六进制字符数组或字符串转换为整数值:
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转换为相应的字节数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接