Search code examples
objective-cswiftswift3uint

Converting Byte to UInt8 (Swift 3)


I have the following code written in 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)];

I have converted it to Swift 3 like so:

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)

However, with this code I am receiving the following error:

enter image description here

How can this be fixed?


Solution

  • The easiest way in Swift 3 to get the two lowest bytes from a 32 bit value is

    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)
    

    This results UInt8 values, to get Data use

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

    If – for some reason – the 32bit value is big endian (most significant byte in the smallest address) then port1Data = data[3] and port2Data = data[2].