In Objective-C I use the following code to
Convert an Int
variable into NSData
, a packet of bytes.
int myScore = 0;
NS
In contemporary versions of Swift, I would do:
let score = 1000
let data = withUnsafeBytes(of: score) { Data($0) }
e8 03 00 00 00 00 00 00
And convert that Data
back to an Int
:
let value = data.withUnsafeBytes {
$0.load(as: Int.self)
}
Note, when dealing with binary representations of numbers, especially when exchanging with some remote service/device, you might want to make the endianness explicit, e.g.
let data = withUnsafeBytes(of: score.littleEndian) { Data($0) }
e8 03 00 00 00 00 00 00
And convert that Data
back to an Int
:
let value = data.withUnsafeBytes {
$0.load(as: Int.self).littleEndian
}
Versus big endian format, also known as “network byte order”:
let data = withUnsafeBytes(of: score.bigEndian) { Data($0) }
00 00 00 00 00 00 03 e8
And convert that Data
back to an Int
:
let value = data.withUnsafeBytes {
$0.load(as: Int.self).bigEndian
}
Needless to say, if you don’t want to worry about endianness, you could use some established standard like JSON (or even XML).
For Swift 2 rendition, see previous revision of this answer.