gpt4 book ai didi

arrays - 我可以使用 UnsafePointer.withMemoryRebound 将 [UInt8] 重新映射到 [UInt16] 吗?

转载 作者:行者123 更新时间:2023-11-28 05:57:10 27 4
gpt4 key购买 nike

我正在尝试将大型 [UInt8] 重新映射到 [UInt16] 中,到目前为止,我的解决方案是这样工作的:

//Function that converts [UInt8] into [UInt16]
func foo(arr: [UInt8])->[UInt16]{
//Split into even and odds
let even = stride(from: 0, to: arr.count, by: 2).map { arr[$0] }
let odd = stride(from: 1, to: arr.count, by: 2).map { arr[$0] }
//pair each even with the next odd
let paired=Array(zip(even, odd))
//reduce UInt8 pairs to UInt16

return paired.reduce([UInt16]()) { (acc, curr) -> [UInt16] in
let u16 = UnsafePointer([curr.0, curr.1]).withMemoryRebound(to: UInt16.self, capacity: 1) {
$0.pointee
}
var newV = acc
newV.append(u16)
return newV
}
}

上面的方法有效,但效率很低。 reduce 函数是大部分计算时间发生的地方。我想知道是否可以直接使用 UnsafePointer.withMemoryRebound 重新映射。我试过:

let test : [UInt16] = UnsafePointer([UInt8(0), UInt8(1),UInt8(0), UInt8(1)]).withMemoryRebound(to: [UInt16].self, capacity: 2) { 
$0.pointee
}

导致:

Execution interrupted. Enter code to recover and continue.
Enter LLDB commands to investigate (type :help for assistance.)
Process 57635 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
frame #0: 0x00007fff7d038d5f libobjc.A.dylib`objc_retain + 15
libobjc.A.dylib`objc_retain:
-> 0x7fff7d038d5f <+15>: movq (%rdi), %rax
0x7fff7d038d62 <+18>: movabsq $0x7ffffffffff8, %rcx ; imm = 0x7FFFFFFFFFF8
0x7fff7d038d6c <+28>: andq %rax, %rcx
0x7fff7d038d6f <+31>: testb $0x2, 0x20(%rcx)
Target 0: (repl_swift) stopped.

也许我误解了它应该如何工作。可以吗?有更好的方法吗?

最佳答案

我的建议是创建一个 Data 实例并使用 withUnsafeBytes 重新映射字节

let arr : [UInt8] = [0x31, 0x32, 0x33, 0x34]
let data = Data(arr)
let u16 = data.withUnsafeBytes {
[UInt16](UnsafeBufferPointer(start: $0, count: data.count/MemoryLayout<UInt16>.stride))
} // [12849, 13363]

关于arrays - 我可以使用 UnsafePointer.withMemoryRebound 将 [UInt8] 重新映射到 [UInt16] 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134402/

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