I'm working on transferring a UInt16
value via BLE. From what I read, for this purpose, I need to convert the UInt16
to UInt8
which will be converted to type Data
. I have been referring to this thread. For example, I've used the code below:
extension Numeric {
var data: Data {
var source = self
return Data(bytes: &source, count: MemoryLayout<Self>.size)
}
}
extension Data {
var array: [UInt8] { return Array(self) }
}
let arr = [16, 32, 80, 160, 288, 400, 800, 1600, 3200]
for x in arr {
let lenghtByte = UInt16(x)
let bytePtr = lenghtByte.bigEndian.data.array
print(lenghtByte, ":", bytePtr)
}
What I can't quite understand is when I convert the UInt16
to a big-endian array, how the values will add up to the corresponding actual value. Hope This makes sense. The output of the above snippet is,
16 : [0, 16]
32 : [0, 32]
80 : [0, 80]
160 : [0, 160]
288 : [1, 32]
400 : [1, 144]
800 : [3, 32]
1600 : [6, 64]
3200 : [12, 128]
What I want to know is how every value after 160 can be calculated using the UInt8
values in a Big-endian array? (i.e. how does [12,128] equate to 3200, likewise).
Thank you in advance :)