Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将int或long转换为字节十六进制数组_Java - Fatal编程技术网

Java 将int或long转换为字节十六进制数组

Java 将int或long转换为字节十六进制数组,java,Java,将整数或长值转换为字节缓冲区的最简单方法是什么 例如: 输入: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]); }

将整数或长值转换为字节缓冲区的最简单方法是什么

例如:

输入: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]);
}

您分配了一个4字节的缓冲区,但在调用
putLong
时,尝试将8字节放入其中。因此溢出。调用ByteBuffer.allocate(8)将防止异常


或者,如果编码的数字是一个整数(如在代码段中),则分配4个字节并调用
putInt()

就足够了。您分配了一个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);
}

对我来说,这是(如果不是最有效的话)转换为字节缓冲区的一种有效方法。

您可以尝试以下更简单的转换方法:

所以你有325647187作为你的输入,然后我们可以有这样的东西

byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();

for (byte b : bytes) 
{
System.out.format("0x%x ", b);
}
对我来说,这是(如果不是最)转换为字节缓冲区的有效方法