将十六进制字符串转换为 Java 中的字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1467005/
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
Convert a hex string to a byte in Java
提问by phpscriptcoder
In Java, how can a hexadecimal string representation of a byte (e.g. "1e") be converted into a byte value?
在 Java 中,如何将字节的十六进制字符串表示(例如“1e”)转换为字节值?
For example:
例如:
byte b = ConvertHexStringToByte("1e");
回答by ZZ Coder
Integer.parseInt(str, 16);
回答by coobird
Byte.parseByte
will return a byte
by parsing a string representation.
Byte.parseByte
将byte
通过解析字符串表示返回 a 。
Using the method with the (String, int)
signature, the radix can be specified as 16, so one can parse a hexadecimal representation of a byte:
使用带(String, int)
签名的方法,可以将基数指定为16,因此可以解析一个字节的十六进制表示:
Byte.parseByte("1e", 16);
回答by Roi A
You can use Byte.parseByte("a", 16);
but this will work only for values up to 127,
values higher then that will need to cast to byte, due to signed/unsigned issues
so i recommend to transfer it to an int and then cast it to byte
您可以使用,Byte.parseByte("a", 16);
但这仅适用于高达 127 的值,高于需要转换为字节的值,由于有符号/无符号问题,因此我建议将其传输到 int,然后将其转换为字节
(byte) (Integer.parseInt("ef",16) & 0xff);