简体   繁体   English

Swift 3:如何将字节数组转换为Data?

[英]Swift 3: How to convert byte array into Data?

I know how to convert int value into data 我知道如何将int值转换为数据

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 现在我想对以以下方式表示的RGB颜色执行相同操作0xRRGGBB

How can I achieve it? 我该如何实现? Should I write it as String, eq "543621", then convert it into byte array then convert it to Data? 我应该将其写为String,即“ 543621”,然后将其转换为字节数组,然后将其转换为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 将颜色存储为UInt32实例似乎是适当的,在这种情况下,您已经发布了一种用于从中初始化Data实例的方法

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: 正如MartinR在下面的评论中指出的那样,要确保十六进制数字表示形式0xCC6699以其小尾数表示形式存储(即使对于采用大尾数主机字节顺序的系统也是如此), pink变量应初始化为:

var pink = UInt32(0xCC6699).littleEndian

// or ...
var pink = UInt32(littleEndian: 0xCC6699)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM