UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How do I get a [UInt32] into a Data?

Forums > Swift

This feels like something there ought to be a straightforward API call for, but I'm not seeing it. So before I go writing the code to turn a UInt32 into two UInt8, I thought I'd ask if anyone knows the right way to do it?

Because, fundamentally, what I'm doing is building an array of 32 bit pixels and then turning it into a CIImage, whose constructor wants a Data. All of which feels way more complicated that I expected; I guess nobody builds bitmaps any more?

2      

Try something lilke this:

import Foundation

//method 1
extension UInt32 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt32>.size)
    }
}

let testInt1 = UInt32.random(in: UInt32.min...UInt32.max)
let data1 = testInt1.data
print(data1)

//method 2
let testInt2 = UInt32.random(in: UInt32.min...UInt32.max)
let data2 = withUnsafeBytes(of: testInt2) { Data($0) }
print(data2)

3      

Nice, that's the sort of thing I was looking for. What I've ultimately gone with is a variation on your method 1:

extension UInt32 {
    var bytes: [UInt8] {
        var bend = bigEndian
        let count = MemoryLayout<UInt32>.size
        let bytePtr = withUnsafePointer(to: &bend) {
            $0.withMemoryRebound(to: UInt8.self, capacity: count) {
                UnsafeBufferPointer(start: $0, count: count)
            }
        }
        return Array(bytePtr)
    }
}

This means that over where I'm transforming my pixel array, it looks like:

  var pixels: [UInt32]

  // ...

  var pixelData = Data()

        for pixel in pixels {
            pixelData.append(contentsOf: pixel.bytes)
        }

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.