在java中将字节数组转换为十六进制时没有得到准确的结果
我正在尝试使用下面的代码从字节缓冲区获取十六进制字符串值。参考: 在Java中,如何将字节数组转换为十六进制数字字符串,同时保留前导零?
public ByteBuffer convert(ByteBuffer in) {
StringBuffer out = new StringBuffer();
for (int iter = 0; iter < in.array().length; iter++) {
byte high = (byte) ( (in.array()[iter] & 0xf0) >> 4);
byte low = (byte) (in.array()[iter] & 0x0f);
out.append(nibble2char(low));
out.append(nibble2char(high));
}
return ByteBuffer.wrap(out.reverse().toString().getBytes());
}
private static char nibble2char(byte b) {
byte nibble = (byte) (b & 0x0f);
if (nibble < 10) {
return (char) ('0' + nibble);
}
return (char) ('a' + nibble - 10);
}
我得到的值是701000000000,实际上我期待这样的值 000000000107。所以我在包装时调用了 stringbuffer 对象的反向方法。
之后我总是得到“ffffff000000” 有人可以帮我解决这个问题吗?
I'm trying to get hex string value from bytebuffer using below code. Reference: In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?
public ByteBuffer convert(ByteBuffer in) {
StringBuffer out = new StringBuffer();
for (int iter = 0; iter < in.array().length; iter++) {
byte high = (byte) ( (in.array()[iter] & 0xf0) >> 4);
byte low = (byte) (in.array()[iter] & 0x0f);
out.append(nibble2char(low));
out.append(nibble2char(high));
}
return ByteBuffer.wrap(out.reverse().toString().getBytes());
}
private static char nibble2char(byte b) {
byte nibble = (byte) (b & 0x0f);
if (nibble < 10) {
return (char) ('0' + nibble);
}
return (char) ('a' + nibble - 10);
}
The value I got as 701000000000, Actually I'm expecting a value like this 000000000107. So I called a reverse method on stringbuffer object at the time of wrapping.
After this I'm always getting "ffffff000000"
Can someone please help me on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论