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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1114381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:13:54  来源:igfitidea点击:

Convert a single hex character to its byte value in java

javahex

提问by nos

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 ais an int or a byte.

如果a是整数还是字节,现在并不重要。

回答by Victor

i don't see why you should have to convert to string... in fact this is what parseInt uses:

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

public static int digit(char ch, int radix)

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.

回答by nos

Found it myself though.

还是自己找的。

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

回答by jqno

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

回答by Nat

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

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

回答by Jon

Take a look at Commons Codec and in particular the Hex class.

看看 Commons Codec,特别是 Hex 类。

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

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:

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

protected static int toDigit(char ch, int index)

You'll need to catch DecoderException though.

不过,您需要捕获 DecoderException。

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.

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