简体   繁体   English

转换UnsafeMutablePointer <Int16> 到UInt8

[英]Convert UnsafeMutablePointer<Int16> to UInt8

I am trying to convert this Int16 mutable pointer to UInt8 to be written on a OutputStream. 我正在尝试将此Int16可变指针转换为要写在OutputStream上的UInt8 I tried to use the function .withMemoryRebound but I don't know how to do it correctly. 我尝试使用.withMemoryRebound函数,但我不知道如何正确执行。 I would like to do it using this function, I tried once but no success. 我想使用此功能来做,我尝试了一次,但没有成功。 I am able to get something working with the code below, but I don't think it is correct. 我可以在下面的代码中工作,但是我认为这是不正确的。

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()

I am currently using Swift 4, is there anything I can do? 我目前正在使用Swift 4,我能做些什么? Thank you and I appreciate your patience. 谢谢,感谢您的耐心配合。

Casting an Unsafe(Mutable)Pointer<Int16> to UnsafePointer<Int8> would simply be: 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM