Swift language, how to convert an array of int type to data type

Swift language, how to convert an array of int type to data type, the array stores 16 decimal numbers, mainly used for network communication

Accepted Answer

plain old data in Swift arrays are contiguous in memory. If the type you are storing were more complex, you may need to use ContiguousArray instead of Array. There are lots of withUnsafeXXX functions, both free and member functions; it took me quite a while to find the right ones. This code generates your array of Int values, makes a Data from the array's data, then makes a new Array from the Data's data. There doesn't seem to be a way to make an Array or even a ContiguousArray directly from a buffer pointer.

import Foundation

let sizeofElement = MemoryLayout<Int>.size

// create array (example is twelve Ints from 1 to 12
var array = Array(1...12)

// create a Data from the bytes in the original array
var data = Data()
array.withUnsafeBufferPointer {
    data = Data(bytes: $0.baseAddress!, count: $0.count * MemoryLayout<Int>.size)
}

// construct a new array by walking through the bytes of data, one Float at a time
// start with an empty array, which we can manipulate in the closure below
var newArray: [Int] = []
data.withUnsafeBytes { rawBufferPtr in 
    rawBufferPtr.withMemoryRebound(to: Int.self) { buffer in // access it as contiguous Int values
        var iter = buffer.makeIterator()
        while let aNumber = iter.next() {
            newArray.append(aNumber)
        }
    }
}

print(array)
print(newArray)
Swift language, how to convert an array of int type to data type
 
 
Q