-3

So lets say I have a class foo with 10 properties all of which are of type String and I want to create a byte array of length 10 like this:

let data = NSData(bytes: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,] as [UInt8], length:10)

Each instance of 0x00 would be a property of class foo. How would I go about creating that?

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"

}

Then the byte array would contain:

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)
Jonathan
  • 614
  • 1
  • 9
  • 18
  • I don't understand what you are asking. You want to break up the bytes from an NSData object into individual properties? Will there always be exactly 10 bytes? And what do the bytes have to do with the strings? Why do you want to do this? Seems like an awkward way to deal with bytes. – Duncan C Apr 08 '16 at 00:51
  • No I want to do just the opposite and create an NSData object from the properties. The properties are in the format of a Strings and need to be converted to bytes. – Jonathan Apr 08 '16 at 00:53
  • And how would you map a string to a single byte? Will each string contain only a single ASCII character? Be clear, man! The first step in figuring a programming problem is a clear, detailed, concrete description of what you need to do. – Duncan C Apr 08 '16 at 00:55
  • a String will look like this "0x5A" – Jonathan Apr 08 '16 at 00:55
  • And what does that represent? This question makes absolutely zero sense. How do you want to map the strings to data? – nhgrif Apr 08 '16 at 01:03
  • I updated the question – Jonathan Apr 08 '16 at 01:11

1 Answers1

0

I solved this by removing the "0x" from the String properties and converting the String to an Int after doing a hex to decimal conversion. Then I just converted it into a UInt8 for my byte array.

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)
Jonathan
  • 614
  • 1
  • 9
  • 18