DCDC DCDC - 6 months ago 90
Swift Question

Swift 3: How to convert byte array into Data?

I know how to convert int value into data

let value: NSInteger = 1
let valueData:Data = Data(buffer: UnsafeBufferPointer(start: &intVal, count: 1))

Now I want to do the same with RGB color denoted in the following way

How can I achieve it? Should I write it as String, e.q. "543621", then convert it into byte array then convert it to Data?


It seems it would be appropriate to store the color as an UInt32 instance, in which case you've already posted a method for initializing a Data instance from it

var pink: UInt32 = 0xCC6699

let pinkData = Data(buffer: UnsafeBufferPointer(start: &pink, count: 1))
print(pinkData.map {$0}) // [153, 102, 204, 0]

print(0x99, 0x66, 0xCC) // 153 102 204