Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.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中将big-endian ByteBuffer写入little-endian_Java_Bytebuffer_Endianness - Fatal编程技术网

如何在Java中将big-endian ByteBuffer写入little-endian

如何在Java中将big-endian ByteBuffer写入little-endian,java,bytebuffer,endianness,Java,Bytebuffer,Endianness,我目前有一个Java ByteBuffer,它已经有了Big-Endian格式的数据。然后我想写一个二进制文件作为Little Endian 下面是刚刚用Big-Endian编写文件的代码: public void writeBinFile(String fileName, boolean append) throws FileNotFoundException, IOException { FileOutputStream outStream = null; try

我目前有一个Java ByteBuffer,它已经有了Big-Endian格式的数据。然后我想写一个二进制文件作为Little Endian

下面是刚刚用Big-Endian编写文件的代码:

 public void writeBinFile(String fileName, boolean append) throws FileNotFoundException, IOException
 {
     FileOutputStream outStream = null;
     try
     {
         outStream = new FileOutputStream(fileName, append);
         FileChannel out = outStream.getChannel();
         byteBuff.position(byteBuff.capacity());
         byteBuff.flip();
         byteBuff.order(ByteOrder.LITTLE_ENDIAN);
         out.write(byteBuff);
     }
     finally
     {
         if (outStream != null)
         {
            outStream.close();
         }
     }

 }
请注意,byteBuff是一个以Big-Endian格式填充的ByteBuffer


我最后的办法是使用蛮力方法创建另一个缓冲区,并将ByteBuffer设置为little endian,然后从原始(big endian)缓冲区读取“getInt”值,并将“setInt”值设置为little endian缓冲区。我想有更好的方法…

Endianess对字节[]没有意义。Endianess仅适用于多字节数据类型,如short、int、long、float或double。正确使用endianess的正确时间是在将原始数据写入字节并读取实际格式时


如果您有一个字节[],则必须解码原始数据类型并使用不同的endianness对其重新编码。我相信您会同意这是a)不容易做到或理想的b)无法自动完成。

以下是我如何解决类似问题的方法,我希望得到我正在写入输出文件的整数的“endianness”正确:

byte[] theBytes = /* obtain a byte array that is the input */
ByteBuffer byteBuffer = ByteBuffer.wrap(theBytes);

ByteBuffer destByteBuffer = ByteBuffer.allocate(theBytes.length);
destByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
IntBuffer destBuffer = destByteBuffer.asIntBuffer();

while (byteBuffer.hasRemaining())
{
    int element = byteBuffer.getInt();

    destBuffer.put(element);

    /* Could write destBuffer int-by-int here, or outside this loop */
}

可能有更有效的方法来实现这一点,但对于我的特殊问题,我必须在将元素复制到新缓冲区时对元素应用数学变换。但这对您的特定问题仍然有效。

您是否为此尝试过Apache commons()?+1用于Apache commons:不重新发明轮子:)