将Swift数据转换为Int16 [英] Converting Swift Data into Int16

查看:309
本文介绍了将Swift数据转换为Int16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台Java服务器,其中放置一个short[],并将其转换为byte[](大端),然后将其发送到iOS设备.我在将此字节数组(或Swift中的Data)转换为int16数组([Int16])时遇到麻烦.我还想知道假设Java short类型的Swift等效项在Swift中是Int16是否正确.

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 converting this byte array (or the Data in Swift) into an int16 array ([Int16]). I was also wondering if I was correct in assuming that the Swift equivalent of a Java short type is a Int16 in Swift.

推荐答案

类似于

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]

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

这篇关于将Swift数据转换为Int16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆