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

拟墨画扇 提交于 2019-12-08 15:06:55

问题


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?


回答1:


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();



回答2:


Two different approaches are described here: http://bytes.com/topic/java/answers/18253-big-endian-vs-little-endian-data. Both would work.




回答3:


  1. Convert from little endian to big endian.
  2. Wrap your converted bytes in ByteBufferInputStream use.
  3. Get your double precision number via DataInputStream.readDouble(in).

Alternatively, you can just take the body of the readDouble method from JDK source and skip step 2 and 3.




回答4:


If you need to read and swap byte order, there is EndianUtils from Commons IO:

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/EndianUtils.html




回答5:


Just use a DataInputStream to read the file, and use the readDouble() method.



来源:https://stackoverflow.com/questions/6471177/converting-8-bytes-of-little-endian-binary-into-a-double-precision-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!