In Objective-C I use the following code to
Convert an Int
variable into NSData
, a packet of bytes.
int myScore = 0;
NS
Swift 5, add an other option.
NSData
is old, still effective
Write Data:
let buffer = NSMutableData()
let size = MemoryLayout.size
let big = 1000
let small = 10
withUnsafeBytes(of: big, { (p) in
let bufferPointer = p.bindMemory(to: UInt.self)
if let address = bufferPointer.baseAddress{
buffer.append(address, length: size)
}
})
withUnsafeBytes(of: small, { (p) in
let bufferPointer = p.bindMemory(to: UInt.self)
if let address = bufferPointer.baseAddress{
buffer.append(address, length: size)
}
})
Read data:
if let d = buffer.copy() as? Data{
var big: UInt = 0
var small: UInt = 0
let size = MemoryLayout.size
let meta = NSData(data: data)
meta.getBytes(&big, range: NSRange(location: 0, length: size))
meta.getBytes(&small, range: NSRange(location: size, length: size))
print("big:", big, "\nsmall:", small)
// big: 1000
// small: 10
}
You know the memory layout, the data put in the memory,
Then put them out exactly.
unsafe
method is funny