所以假设我有一个包含10个属性的类foo,所有属性都是String类型,我想创建一个长度为10的字节数组,如下所示:
let data = NSData(bytes: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,] as [UInt8], length:10)
0x00的每个实例都是类foo的属性。我该怎么做呢?
class foo {
var mailbox = "0x00"
var cmd = "0x00"
var data0 = "0x00"
var data1 = "0x00"
var data2 = "0x00"
var data3 = "0x00"
var data4 = "0x00"
var data5 = "0x00"
var data6 = "0x00"
var data7 = "0x00"
}
然后字节数组将包含:
let data = NSData(bytes:[foo.mailbox, foo.cmd, foo.data0, foo.data1, foo.data2, foo.data3, foo.data4, foo.data5, foo.data6, foo.data7] as [UInt8], length:10)
答案 0 :(得分:0)
我通过从String属性中删除“0x”并在执行十六进制到十进制转换后将String转换为Int来解决此问题。然后我只是将它转换为我的字节数组的UInt8。
let mailbox = Int(converttoDec(foo.mailbox.stringByReplacingOccurrencesOfString("0x", withString: ""))
let data = NSData(bytes:[UInt8(mailbox!), UInt8(command!), UInt8(data0!), UInt8(data1!), UInt8(data2!), UInt8(data3!), UInt8(data4!), UInt8(data5!), UInt8(data6!), UInt8(data7!),] as [UInt8], length:10)