简体   繁体   中英

How can I convert my UInt8 array to Data? (Swift)

I am trying to communicate with a Bluetooth laser tag gun that takes data in 20 byte chunks, which are broken down into 16, 8 or 4-bit words. To do this, I made a UInt8 array and changed the values in there. The problem happens when I try to send the UInt8 array.

            var bytes = [UInt8](repeating: 0, count: 20)
            bytes[0] = commandID
            if commandID == 240 {
                commandID = 0
            }
            commandID += commandIDIncrement
            
            print(commandID)
            bytes[2] = 128
            bytes[4] = UInt8(gunIDSlider.value)
            print("Response: \(laserTagGun.writeValue(bytes, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")

commandID is just a UInt8. This gives me the error, Cannot convert value of type '[UInt8]' to expected argument type 'Data' , which I tried to solve by doing this:

var bytes = [UInt8](repeating: 0, count: 20)

    bytes[0] = commandID
    if commandID == 240 {
        commandID = 0
    }
    commandID += commandIDIncrement
    print(commandID)

    bytes[2] = 128
    bytes[4] = UInt8(gunIDSlider.value)
    print("bytes: \(bytes)")

    assert(bytes.count * MemoryLayout<UInt8>.stride >= MemoryLayout<Data>.size)
    let data1 = UnsafeRawPointer(bytes).assumingMemoryBound(to: Data.self).pointee
    print("data1: \(data1)")

    print("Response: \(laserTagGun.writeValue(data1, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")
    

To this, data1 just prints 0 bytes and I can see that laserTagGun.writeValue isn't actually doing anything by reading data from the other characteristics. How can I convert my UInt8 array to Data in swift? Also please let me know if there is a better way to handle 20 bytes of data than a UInt8 array. Thank you for your help!

It looks like you're really trying to avoid a copy of the bytes, if not, then just init a new Data with your bytes array:

let data2 = Data(bytes)
print("data2: \(data2)")

If you really want to avoid the copy, what about something like this?

let data1 = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: bytes.count, deallocator: .none)
print("data1: \(data1)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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