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 0xRRGGBB
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?
答案 0 :(得分:1)
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
As MartinR points out in a comment below, to ensure the hex number representation 0xCC6699
is stored in its little endian representation (even for systems which employ big endian host byte order), the pink
variable should be initialized as:
var pink = UInt32(0xCC6699).littleEndian
// or ...
var pink = UInt32(littleEndian: 0xCC6699)