gpt4 book ai didi

swift - 如何在 Swift 3 中将 UInt16 转换为 UInt8?

转载 作者:搜寻专家 更新时间:2023-11-01 05:46:56 24 4
gpt4 key购买 nike

我想将 UInt16 数组转换为 UInt8 数组,但收到以下错误消息:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

代码:

    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 变量的存储。由于 UnsafeRawBufferPointerUInt8Sequence,因此数组可以用 Array($0) 创建。

关于swift - 如何在 Swift 3 中将 UInt16 转换为 UInt8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com