Java代码将字节转换为十六进制 [英] Java code To convert byte to Hexadecimal
问题描述
我有一个字节数组.我希望将该数组的每个字节字符串转换为其相应的十六进制值.
I have an array of bytes. I want each byte String of that array to be converted to its corresponding hexadecimal values.
Java 中是否有将字节数组转换为十六进制的函数?
Is there any function in Java to convert a byte array to Hexadecimal ?
推荐答案
byte[] bytes = {-1, 0, 1, 2, 3 };
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
// prints "FF 00 01 02 03 "
另见
java.util.Formatter
语法%[flags][width]转换
- Flag
'0'
- 结果将被补零 - 宽度
2
- 转换
'X'
- 结果被格式化为十六进制整数,大写 java.util.Formatter
syntax%[flags][width]conversion
- Flag
'0'
- The result will be zero-padded - Width
2
- Conversion
'X'
- The result is formatted as a hexadecimal integer, uppercase
查看问题的文本,这也可能是请求的内容:
Looking at the text of the question, it's also possible that this is what is requested:
String[] arr = {"-1", "0", "10", "20" }; for (int i = 0; i < arr.length; i++) { arr[i] = String.format("%02x", Byte.parseByte(arr[i])); } System.out.println(java.util.Arrays.toString(arr)); // prints "[ff, 00, 0a, 14]"
<小时>
这里的几个答案使用
Integer.toHexString(int)
;这是可行的,但有一些警告.由于参数是一个int
,所以对byte
参数执行了扩展原始转换,这涉及符号扩展.
Several answers here uses
Integer.toHexString(int)
; this is doable, but with some caveats. Since the parameter is anint
, a widening primitive conversion is performed to thebyte
argument, which involves sign extension.byte b = -1; System.out.println(Integer.toHexString(b)); // prints "ffffffff"
在 Java 中签名的 8 位
byte
被符号扩展为 32 位int
.为了有效地撤销这个符号扩展,可以用0xFF
屏蔽byte
.The 8-bit
byte
, which is signed in Java, is sign-extended to a 32-bitint
. To effectively undo this sign extension, one can mask thebyte
with0xFF
.byte b = -1; System.out.println(Integer.toHexString(b & 0xFF)); // prints "ff"
使用
toHexString
的另一个问题是它没有用零填充:Another issue with using
toHexString
is that it doesn't pad with zeroes:byte b = 10; System.out.println(Integer.toHexString(b & 0xFF)); // prints "a"
结合这两个因素应该使
String.format
解决方案更受欢迎.Both factors combined should make the
String.format
solution more preferrable.- JLS 4.2.1 积分类型和值
- 对于
byte
,从-128
到127
,包括
- JLS 4.2.1 Integral Types and Values
- For
byte
, from-128
to127
, inclusive
这篇关于Java代码将字节转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- For
- 对于
- Flag
See also
- Flag