java字节转16进制,Java代码将字节转换为十六进制

该博客介绍了如何在Java中将字节数组转换为对应的十六进制表示。通过使用`String.format`方法和`StringBuilder`,可以逐个处理字节并以零填充的十六进制格式添加到字符串中。此外,还讨论了`Integer.toHexString`方法的使用及其可能遇到的问题,包括符号扩展和零填充。示例代码展示了如何实现这个转换过程。
摘要由CSDN通过智能技术生成

I have an array of bytes.

I want each byte String of that array to be converted to its corresponding hexadecimal values.

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 "

See also

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]"

Several answers here uses Integer.toHexString(int); this is doable, but with some caveats. Since the parameter is an int, a widening primitive conversion is performed to the byte argument, which involves sign extension.

byte b = -1;

System.out.println(Integer.toHexString(b));

// prints "ffffffff"

The 8-bit byte, which is signed in Java, is sign-extended to a 32-bit int. To effectively undo this sign extension, one can mask the byte with 0xFF.

byte b = -1;

System.out.println(Integer.toHexString(b & 0xFF));

// prints "ff"

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"

Both factors combined should make the String.format solution more preferrable.

References

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值