Converting Swift Data into Int16

前端 未结 1 814
南笙
南笙 2020-12-22 06:44

I have a Java server where I take a short[] and I convert it to a byte[] (Big Endian) and I send it to an iOS device. I am having trouble converti

相关标签:
1条回答
  • 2020-12-22 07:10

    Similarly as in round trip Swift number types to/from Data you can use the withUnsafeBytes method and UnsafeBufferPointer<Int16> to get a view of the data as 16-bit integers. Then use the Int16(bigEndian:) initializer to convert the numbers from big endian to host byteorder. Example:

    let data = Data(bytes: [0, 1, 0, 2, 1, 0, 255, 255])
    let i16array = data.withUnsafeBytes {
        UnsafeBufferPointer<Int16>(start: $0, count: data.count/2).map(Int16.init(bigEndian:))
    }
    print(i16array) // [1, 2, 256, -1]
    

    Update for Swift 5:

    let data = Data([0, 1, 0, 2, 1, 0, 255, 255])
    let i16array = data.withUnsafeBytes {
            Array($0.bindMemory(to: Int16.self)).map(Int16.init(bigEndian:))
        }
    print(i16array) // [1, 2, 256, -1]
    
    0 讨论(0)
提交回复
热议问题