如何将UInt16转换为Swift 3中的UInt8?
问题描述:
我想UINT16转换为UINT8数组,但我得到了以下错误消息:如何将UInt16转换为Swift 3中的UInt8?
“初始化”不可用:使用“withMemoryRebound(到:容量:__)”来 暂时查看内存作为另一个布局兼容型。
代码:
let statusByte: UInt8 = UInt8(status)
let lenghtByte: UInt16 = UInt16(passwordBytes.count)
var bigEndian = lenghtByte.bigEndian
let bytePtr = withUnsafePointer(to: &bigEndian) {
UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian))
}
答
作为错误消息表示,则必须使用withMemoryRebound()
重新解释指针UInt16
作为指针以UInt8
:
let bytes = withUnsafePointer(to: &bigEndian) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: bigEndian)) {
Array(UnsafeBufferPointer(start: $0, count: MemoryLayout.size(ofValue: bigEndian)))
}
}
封闭件与指针($0
),其是唯一的调用有效期为 ,并且不得传递给外部 供以后使用。这就是为什么Array
被创建并用作返回值的原因。
然而有一个简单的解决方案:
let bytes = withUnsafeBytes(of: &bigEndian) { Array($0) }
说明:withUnsafeBytes
调用与一个UnsafeRawBufferPointer
封闭到bigEndian
变量的存储。 由于UnsafeRawBufferPointer
是Sequence
的UInt8
,因此可以使用Array($0)
创建一个数组 。
答
您可以扩展整数协议和创建数据属性如下:
extension Integer {
var data: Data {
var source = self
return Data(bytes: &source, count: MemoryLayout<Self>.size)
}
}
在斯威夫特3数据符合MutableCollection所以你可以创建一个数组来自您的UInt16数据的字节:
extension Data {
var array: [UInt8] { return Array(self) }
}
let lenghtByte = UInt16(8)
let bytePtr = lenghtByte.bigEndian.data.array // [0, 8]