将字节转换为 UInt8 (Swift 3)

Converting Byte to UInt8 (Swift 3)

我在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)

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

如何解决这个问题?

Swift3 中从 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]