如何在Java中将大字节序ByteBuffer写入小字节序 [英] How write big endian ByteBuffer to little endian in Java

查看:475
本文介绍了如何在Java中将大字节序ByteBuffer写入小字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个Java ByteBuffer,它已经具有Big Endian格式的数据。然后,我想以Little Endian的形式写入二进制文件。

I currently have a Java ByteBuffer that already has the data in Big Endian format. I then want to write to a binary file as Little Endian.

这是只将文件写入Big Endian的代码:

Here's the code which just writes the file still in 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。

Note that byteBuff is a ByteBuffer that has been filled in Big Endian format.

我的最后一招是蛮力创建另一个缓冲区并将ByteBuffer设置为little endian然后读取的方法原始缓冲区(大字节序)中的 getInt值,而小字节序缓冲区中的值 setInt。我想有一种更好的方法...

My last resort is a brute force method of creating another buffer and setting that ByteBuffer to little endian and then reading the "getInt" values from the original (big endian) buffer, and "setInt" the value to the little endian buffer. I'd imagine there is a better way...

推荐答案

Endianess对byte []没有意义。 Endianess仅对多字节数据类型(如short,int,long,float或double)起作用。获得正确性的正确时机是将原始数据写入字节并读取实际格式时。

Endianess has no meaning for a byte[]. Endianess only matter for multi-byte data types like short, int, long, float, or double. The right time to get the endianess right is when you are writing the raw data to the bytes and reading the actual format.

如果给定了byte [],则必须解码原始数据类型,然后以不同的字节序重新编码。我相信您会同意这是a)不容易做到或不理想b)无法自动完成。

If you have a byte[] given to you, you must decode the original data types and re-encode them with the different endianness. I am sure you will agree this is a) not easy to do or ideal b) cannot be done automagically.

这篇关于如何在Java中将大字节序ByteBuffer写入小字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆