How to write a large endian ByteBuffer for a small endian in Java

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

Here's the code that just writes the file back to 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();
         }
     }

 }

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

My last resort is the brute force method of creating another buffer and setting the ByteBuffer to a small value and then reading the β€œgetInt” values ​​from the source (large end) buffer and the β€œsetInt” value to the small end of the buffer. I would suggest that there is a better way. ..

+5
source share
2 answers

Endianess []. Endianess , short, int, long, float double. , endianess, - .

[], , . , , a) b) .

+4

, "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 */
}

, , . - .

+3

All Articles