可以安全地反转Double的字节顺序吗? [英] Can the byte order of Double be safely reversed?

查看:57
本文介绍了可以安全地反转Double的字节顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Double 在内存中使用8个字节表示.我认为这8个字节应包含两个部分,每个部分用于整数部分,一个部分用于小数部分(如果我在此假设中错了,请纠正我).我的机器有点小尾声(现在每个Macmini都是).我想将表示 Double 的这8个字节传输到文件,该文件应在BigEndian平台(尤其是JVM)上可读.

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.

考虑到具有两个组成部分的 Double ,简单地颠倒字节顺序是否安全?如果不安全,该如何将LittleEndian数据表示为BidEndian数据?

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?

我还需要读取一个包含BigEndian数据的文件,并将其转换为LittleEndian计算机上的 Double .恰好相反.

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

推荐答案

有一个

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:

位模式与IEEE 754规范定义的二进制交换格式匹配.

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

因此-假设JVM使用相同的IEEE 754二进制交换格式-以下内容将是安全的:

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) }

反方向:

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

这篇关于可以安全地反转Double的字节顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆