Can the byte order of Double be safely reversed?

前提是你 提交于 2021-01-28 21:20:47

问题


Double is represented in memory using 8 bytes. I believe these 8 bytes should be having two components, one each for integer-part and one for the fractional-part(Correct me if I am wrong in this assumption). My machine is a little endian(Nowadays every Macmini is). I want to transfer these 8 bytes representing Double to a file, which should be readable on a BigEndian platform(Specifically JVM which is BE).

It is safe for plain Integers to reverse the byte order, as they don't have components and are atomic.

Is it safe to simply reverse the byte order for Double considering it has the two components? If its not safe how do I go about representing the LittleEndian data to BidEndian data?

Also I need to read a file containing BigEndian data and convert it to Double on my LittleEndian machine. Exactly the reverse scenario.


回答1:


There is a bitPattern method to get the bit pattern of a floating point value as an integer, and a Double(bitPattern:) initializer for the reverse conversion. From the documentation:

The bit pattern matches the binary interchange format defined by the IEEE 754 specification.

Therefore – assuming that the JVM uses the same IEEE 754 binary interchange format – the following would be safe:

let x = 12.34

// Double to binary interchange format (big endian):
let data = withUnsafeBytes(of: x.bitPattern.bigEndian) { Data($0) }

And for the reverse direction:

// Binary interchange format (big endian) to Double:
let y = data.withUnsafeBytes { Double(bitPattern: UInt64(bigEndian: $0.load(as: UInt64.self))) }


来源:https://stackoverflow.com/questions/56167127/can-the-byte-order-of-double-be-safely-reversed

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