相关疑难解决方法(0)

在Swift中将两个字节的UInt8数组转换为UInt16

使用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
Run Code Online (Sandbox Code Playgroud)

Swift尝试:

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 …
Run Code Online (Sandbox Code Playgroud)

swift

29
推荐指数
4
解决办法
2万
查看次数

标签 统计

swift ×1