Reimond Hill
Reimond Hill

Reputation: 4760

Int16 to Byte array wrong array order swift 4

i am trying to convert a Int16 into [UInt8] like that:

var track:Int16 = 4
let trackData = Data(bytes: &track, count: 2)

but the result is

[4, 0]

I was wondering if there is a way to get

[0, 4]

So when I do :

let value = Int16(bigEndian: trackData.withUnsafeBytes { $0.pointee })

I would get 4 instead of 1024

Upvotes: 0

Views: 180

Answers (1)

holex
holex

Reputation: 24031

it is not much a rocket-science but byteSwapped may do the job for you, like:

let value = Int16(bigEndian: trackData.withUnsafeBytes { $0.pointee }).byteSwapped

that would make the value 4 in your case.


NOTE: even Apple Docs does not say too much about this property (kinda self explanatory, to be honest), so just for the sake of completion, here comes the reference of byteSwapped.

Upvotes: 1

Related Questions