2017-03-17 99 views
0

我已經寫在Objective-C以下代碼:轉換字節到UINT8(SWIFT 3)

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)]; 

我已轉換它爲夫特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

如何這個問題能解決?

回答

3

斯威夫特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]