将Swift数据转换为Int16

时间:2017-07-17 16:37:07

标签: java ios swift

我有一个Java服务器,我在其中short[]并将其转换为byte[](Big Endian)并将其发送到iOS设备。我无法将此字节数组(或Swift中的Data)转换为int16数组([Int16])。我也想知道我是否正确假设Swift相当于Java short类型在Swift中是Int16

1 个答案:

答案 0 :(得分:2)

round trip Swift number types to/from Data类似,您可以使用withUnsafeBytes 方法和UnsafeBufferPointer<Int16>以获取数据视图 16位整数。然后使用Int16(bigEndian:)初始值设定项进行转换 从大端到主机字节顺序的数字。例如:

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]

更新 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]