问题描述
我有一台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.
推荐答案
类似于,您可以使用withUnsafeBytes
方法和UnsafeBufferPointer<Int16>
获取数据的视图为16位整数.然后使用Int16(bigEndian:)
初始化程序进行转换从大端到主机字节序的数字.示例:
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 as16-bit integers. Then use the Int16(bigEndian:)
initializer to convertthe 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!