Simon Youens Simon Youens - 2 months ago 29
Swift Question

Swift 4 - efficient conversion of Double to big-endian

I need to convert a Double to big-endian in order to write it to a file, using an oil-industry binary file standard, that was originally defined for IBM half-inch 9 track tapes in the 1970s!

I need really efficient Swift 4 code, because this conversion is inside two nested-loops and will be executed upwards of 100,000 times.

Answer Source

You can create an UInt64 containing the big-endian representation of the Double with

let value = 1.0
var n = value.bitPattern.bigEndian

In order to write that to a file you might need to convert it to Data:

let data = Data(buffer: UnsafeBufferPointer(start: &n, count: 1))
print(data as NSData) // <3ff00000 00000000>

If many contiguous floating point values are written to the file then it would be more effective to create an [UInt64] array with the big-endian representations and convert that to Data, for example

let values = [1.0, 2.0, 3.0, 4.0]
let array = { $0.bitPattern.bigEndian }
let data = array.withUnsafeBufferPointer { Data(buffer: $0) }

(All the above compiles with Swift 3 and 4.)