eklektek
eklektek

Reputation: 1173

swift extracting bytes from struct Data

data is arriving in the form of struct Data size count == 5 the last 3 bytes contain an ID that needs to be extracted.

The following code works, however I am sure it could be greatly improved (as you can tell I am new to swift!):

var data:[UInt8] = [ 0xff, 0xff, 0x01, 0x02 ,0x03 ]
var txData = Data(bytes: data)
print(txData.count)
let byte00 = txData.subdata(in: 2..<3 ).withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt8 in
    return ptr.pointee
}
let byte01 = txData.subdata(in: 3..<4 ).withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt8 in
    return ptr.pointee
}
let byte02 = txData.subdata(in: 4..<5 ).withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt8 in
    return ptr.pointee
}

let rxData = (UInt(byte00) << 16) + (UInt(byte01) << 8) + UInt(byte02)
print( String(rxData, radix:16) )

Any tutorial recommendations covering this area of swift would be greatly appreciated.

Upvotes: 0

Views: 691

Answers (1)

OOPer
OOPer

Reputation: 47876

You can write something like this:

var data:[UInt8] = [ 0xff, 0xff, 0x01, 0x02 ,0x03 ]
var txData = Data(bytes: data)
print(txData.count)
let byte00 = txData[2]
let byte01 = txData[3]
let byte02 = txData[4]

let rxData = (UInt(byte00) << 16) + (UInt(byte01) << 8) + UInt(byte02)
print( String(rxData, radix:16) ) //->10203

In Swift 3, Data can be treated as a Collection of UInt8, you can subscript to Data directly when getting each byte as UInt8.

And as 3 byte is not a good number for the current CPUs, the code above cannot be much shorter.

Upvotes: 2

Related Questions