将 UnsafeMutablePointer<Int16> 转换为 UInt8
Posted
技术标签:
【中文标题】将 UnsafeMutablePointer<Int16> 转换为 UInt8【英文标题】:Convert UnsafeMutablePointer<Int16> to UInt8 【发布时间】:2018-02-15 17:41:40 【问题描述】:我正在尝试将此Int16
可变指针转换为UInt8
以写入输出流。我尝试使用函数.withMemoryRebound
,但我不知道如何正确使用。我想用这个功能来做,我试过一次但没有成功。我可以使用下面的代码得到一些东西,但我认为它不正确。
unwrappedOutputStream.open()
let buffer: UnsafeMutablePointer<Int16> = avAudioPCMBuffer.int16ChannelData![0]
let size = MemoryLayout<UInt8>.size
let bound: UnsafeMutablePointer<UInt16> = UnsafeMutablePointer.allocate(capacity: 1)
bound.pointee = UInt16(bitPattern: buffer.pointee)
let bytePointer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.allocate(capacity: 1)
bytePointer.pointee = UInt8(bound.pointee >> 0x8)
unwrappedOutputStream.write(bytePointer, maxLength: size)
bytePointer.pointee = UInt8(bound.pointee & 0xff)
unwrappedOutputStream.write(bytePointer, maxLength: size)
bound.deallocate(capacity: 1)
bytePointer.deallocate(capacity: 1)
unwrappedOutputStream.close()
我目前正在使用 Swift 4,有什么可以做的吗? 谢谢你,感谢你的耐心。
【问题讨论】:
flushData.buffer
是否指向您要写入的数据?它是指向单个 Int16 值还是指向值数组?您想按主机字节顺序还是按 bigendian 写入值?
@MartinR 我认为它指向int16ChannelData
上使用的AVAudioPCMBuffer
数组的第一个数组。直接翻译成avAudioPCMBuffer.int16ChannelData![0]
。
代码更新:)
对答案有任何反馈吗?
对不起,谢谢您的回答。
【参考方案1】:
将Unsafe(Mutable)Pointer<Int16>
转换为UnsafePointer<Int8>
只是:
let buffer: UnsafeMutablePointer<Int16> = ...
let count: Int = ... // # of Int16 values
let result = buffer.withMemoryRebound(to: UInt8.self, capacity: 2 * count)
outputStream.write($0, maxLength: 2 * count)
【讨论】:
以上是关于将 UnsafeMutablePointer<Int16> 转换为 UInt8的主要内容,如果未能解决你的问题,请参考以下文章
swift3.0 无法将类型“[UnsafeMutablePointer<Int8>]”的值转换为预期的参数类型“UnsafeMutablePointer<Int8>?”
UnsafeMutablePointer<Float> 到 UnsafeMutablePointer<_>
iOS:将 UnsafeMutablePointer<Int8> 快速转换为字符串?
如何将 UnsafeMutablePointer<Void> 转换为 UInt8?