0

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?

4
  • In Swift 3 you can even initialize the data let valueData = Data([1]) Commented Oct 20, 2016 at 13:01
  • @vadian Could you provide the code snippet how would initialize Data of hex string to get color as data? Commented Oct 20, 2016 at 13:04
  • 1
    Is your input a (hex) string or an integer? Commented Oct 20, 2016 at 13:04
  • @MartinR which one would be more convenient to initliaze it? It does not matter, can be string, can be int, the point is I have to update value on bluetooth peripheral by this hex color so I need to convert it into Data Commented Oct 20, 2016 at 13:06

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Strictly speaking it should be var pink = UInt32(0xCC6699).littleEndian to make the data independent of the host byte order. How knows to which platform Swift will be ported in the future?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.