I tried to see if I could reproduce the unexpected behavior you describe using this program:
import Foundation
func test() {
var data = Data()
data.append(contentsOf: [
26, // Initial byte stating the remaining number of bytes
11, 12, 13, 14, // bytes of 1st UInt32 value
21, 22, 23, 24, // bytes of 2nd UInt32 value
31, 32, 33, 34, // bytes of 3rd UInt32 value
41, 42, 43, 44, // bytes of 4th UInt32 value
51, 52, 53, 54, // bytes of 5th UInt32 value
61, 62, // bytes of 1st UInt16
71, 72, // bytes of 2nd UInt16
81, 82, // bytes of 3rd UInt16
])
print("data:", data.map(String.init).joined(separator: ", "))
let payload = data.advanced(by: 1)
print("payload:", payload.map(String.init).joined(separator: ", "))
let slicedBuffer = payload.advanced(by: 20)
print("slicedBuffer:", slicedBuffer.map(String.init).joined(separator: ", "))
slicedBuffer.withUnsafeBytes { ptr in
print("UInt16 values:")
for uint16Index in 0 ..< ptr.count/2 {
let uint16Value = ptr.load(fromByteOffset: uint16Index * 2, as: UInt16.self)
print(uint16Value, "( low byte:", uint16Value & 0xff, ", high byte:", uint16Value >> 8, ")")
}
}
}
test()
But couldn't, as the output is as expected:
data: 26, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 71, 72, 81, 82
payload: 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 71, 72, 81, 82
slicedBuffer: 61, 62, 71, 72, 81, 82
UInt16 values:
15933 ( low byte: 61 , high byte: 62 )
18503 ( low byte: 71 , high byte: 72 )
21073 ( low byte: 81 , high byte: 82 )