0

I have a java.nio.MappedByteBuffer that I am using to read integers from a little-endian file. I set the byte order to LITTLE_ENDIAN using ByteBuffer.order(), but this causes the buffer to interpret integers as if they were big endian.

Confirm that we have the number 3 in little endian in bytes 4-7

>> sprintf( '%.2x ', qfunction.s_idx.get(4), qfunction.s_idx.get(5), qfunction.s_idx.get(6), qfunction.s_idx.get(7) )

ans =

03 00 00 00 

Reading as LITTLE_ENDIAN returns 0x03000000 instead of 0x00000003!

>> qfunction.s_idx.order( java.nio.ByteOrder.LITTLE_ENDIAN );
>> sprintf( '%.8x', qfunction.s_idx.getInt(1) )

ans =

03000000

Reading as BIG_ENDIAN does return 3!*

>> qfunction.s_idx.order( java.nio.ByteOrder.BIG_ENDIAN );
>> sprintf( '%.8x', qfunction.s_idx.getInt(1) )

ans =

00000003

What is going on here?

Using Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) 64-Bit Server VM mixed mode Using MATLAB R2011b

Clark
  • 890
  • 8
  • 20

1 Answers1

2

You are writing bytes 4,5,6,7 but reading bytes 1,2,3,4. This makes byte 4 (which is the only one with a value) appear at the end instead of the start,

Try instead

>> sprintf( '%.8x', qfunction.s_idx.getInt(4) )
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • You sir, are a gentleman and a scholar. To clarify for others, I was treating the argument of ByteBuffer.getInt() as if it were an index into an array of integers (1 = "I want the second integer) when its is really a byte offset. – Clark Apr 19 '12 at 18:38
  • Perhaps `IntBuffer ib = byteBuffer.asIntBuffer();` is more to your liking. ;) – Peter Lawrey Apr 19 '12 at 19:44