簡體   English   中英

轉換UnsafeMutablePointer <Int16> 到UInt8

[英]Convert UnsafeMutablePointer<Int16> to UInt8

我正在嘗試將此Int16可變指針轉換為要寫在OutputStream上的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,我能做些什么? 謝謝,感謝您的耐心配合。

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