Converting 8 bytes of little-endian binary into a double precision float

RedLeader picture RedLeader · Jun 24, 2011 · Viewed 8.5k times · Source

I have a binary file that I read byte by byte.

I come across a section that is 8 bytes long, holding a double precision float (little endian). I can't figure out how to read this in and calculate it properly with masking and/or casting.

(To be specific, the file type is .LAS, but that shouldn't matter).

Are there any Java tricks?

Answer

Peter Lawrey picture Peter Lawrey · Jun 24, 2011

You can use ByteBuffer

from a byte[] bytes

 double d = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN ).getDouble();

from a Socket

 ByteBuffer bb = ByteBuffer.allocate(64*1024).order(ByteOrder.LITTLE_ENDIAN );
 socket.read(bb);
 bb.flip();
 double d = bb.getDouble();