将字节转换为UInt8(Swift 3)

时间:2017-03-17 11:25:35

标签: objective-c swift swift3 uint

我有以下用Objective-C编写的代码:

int port1 = SERVER_DEVICE_PORT;
int port2 = SERVER_DEVICE_PORT>>8;

Byte port1Byte[1] = {port1};
Byte port2Byte[1] = {port2};

NSData *port1Data = [[NSData alloc]initWithBytes: port1Byte length: sizeof(port1Byte)];
NSData *port2Data = [[NSData alloc]initWithBytes: port2Byte length: sizeof(port2Byte)];

我已将其转换为Swift 3,如下所示:

let port1: Int = Int(SERVER_DEVICE_PORT)
let port2: Int = Int(SERVER_DEVICE_PORT) >> 8

let port1Bytes: [UInt8] = [UInt8(port1)]
let port2Bytes: [UInt8] = [UInt8(port2)]

let port1Data = NSData(bytes: port1Bytes, length: port1)
let port2Data = NSData(bytes: port2Bytes, length: port2)

但是,使用此代码我收到以下错误:

enter image description here

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

Swift 3中从32位值获取两个最低字节的最简单方法是

var SERVER_DEVICE_PORT : Int32 = 55056

let data = Data(buffer: UnsafeBufferPointer(start: &SERVER_DEVICE_PORT, count: 1))
// or let data = Data(bytes: &SERVER_DEVICE_PORT, count: 2)
let port1Data = data[0]
let port2Data = data[1]

print(port1Data, port2Data)

这会产生UInt8值,以便Data使用

let port1Data = Data([data[0]])
let port2Data = Data([data[1]])

如果 - 由于某种原因 - 32位值是大端(最小地址中最重要的字节),那么port1Data = data[3]port2Data = data[2]