NEW: Learn to build the incredible iOS 15 Weather app today! >>

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?

   

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)

1      

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

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.