Search code examples
swiftunsafemutablepointer

Convert UnsafeMutablePointer<Int16> to UInt8


I am trying to convert this Int16 mutable pointer to UInt8 to be written on a OutputStream. I tried to use the function .withMemoryRebound but I don't know how to do it correctly. 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? Thank you and I appreciate your patience.


Solution

  • Casting an Unsafe(Mutable)Pointer<Int16> to UnsafePointer<Int8> would simply be:

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