将 UnsafeMutablePointer<Int16> 转换为 UInt8
Convert UnsafeMutablePointer<Int16> to UInt8
我正在尝试将此 Int16
可变指针转换为 UInt8
以写入 OutputStream。我尝试使用函数 .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、有什么可以做的吗?
谢谢你,感谢你的耐心等待。
正在将 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([=10=], maxLength: 2 * count)
}
我正在尝试将此 Int16
可变指针转换为 UInt8
以写入 OutputStream。我尝试使用函数 .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、有什么可以做的吗? 谢谢你,感谢你的耐心等待。
正在将 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([=10=], maxLength: 2 * count)
}