使用Swift,我想将字节从uint8_t数组转换为整数。
“ C”示例:
char bytes[2] = {0x01, 0x02}; NSData *data = [NSData dataWithBytes:bytes length:2]; NSLog(@"data: %@", data); // data: <0102> uint16_t value2 = *(uint16_t *)data.bytes; NSLog(@"value2: %i", value2); // value2: 513
快速尝试:
let bytes:[UInt8] = [0x01, 0x02] println("bytes: \(bytes)") // bytes: [1, 2] let data = NSData(bytes: bytes, length: 2) println("data: \(data)") // data: <0102> let integer1 = *data.bytes // This fails let integer2 = *data.bytes as UInt16 // This fails let dataBytePointer = UnsafePointer<UInt16>(data.bytes) let integer3 = dataBytePointer as UInt16 // This fails let integer4 = *dataBytePointer as UInt16 // This fails let integer5 = *dataBytePointer // This fails
从Swift中的UInt8数组创建UInt16值的正确语法或代码是什么?
我对NSData版本感兴趣,并且正在寻找不使用临时数组的解决方案。
如果您想通过NSData,它将像这样工作:
NSData
let bytes:[UInt8] = [0x01, 0x02] println("bytes: \(bytes)") // bytes: [1, 2] let data = NSData(bytes: bytes, length: 2) print("data: \(data)") // data: <0102> var u16 : UInt16 = 0 ; data.getBytes(&u16) // Or: let u16 = UnsafePointer<UInt16>(data.bytes).memory println("u16: \(u16)") // u16: 513
或者:
let bytes:[UInt8] = [0x01, 0x02] let u16 = UnsafePointer<UInt16>(bytes).memory print("u16: \(u16)") // u16: 513
两种变体都假定字节按主机字节顺序排列。
Swift 3(Xcode 8)更新:
let bytes: [UInt8] = [0x01, 0x02] let u16 = UnsafePointer(bytes).withMemoryRebound(to: UInt16.self, capacity: 1) { $0.pointee } print("u16: \(u16)") // u16: 513