![](/img/trans.png)
[英]How to convert byte array to hex string which it is using for convert it to long?
[英]convert int or long to byte hex array
将整数或长值转换为字节缓冲区的最简单方法是什么?
例:
输入:325647187
输出:{0x13,0x68,0xfb,0x53}
我已经尝试过像这样的ByteBuffer:
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putLong(325647187);
byte[] x=buffer.array();
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
但我例外
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:527)
at java.nio.HeapByteBuffer.putLong(HeapByteBuffer.java:423)
at MainApp.main(MainApp.java:11)
您分配了一个4字节的缓冲区,但是在调用putLong
,您试图在其中放入8个字节。 因此,溢出。 调用ByteBuffer.allocate(8)
将阻止该异常。
或者,如果编码的数字是整数(如您的代码段所示),则足以分配4个字节并调用putInt()
。
您可以尝试此方法,以实现更简单的转换方式:
所以您输入325647187作为输入,然后我们可以输入如下内容
byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();
for (byte b : bytes)
{
System.out.format("0x%x ", b);
}
对我来说,这(如果不是最多的话)是一种转换为字节缓冲区的有效方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.