2

i need to convert hex string to byte array using swift. I have tried with following example hex string

"7B737369643A32333A34333A34353A31352C70617373776F72643A31323334357D"

This is my code

func sendCmd (CMD: [UInt8],length: Int ,hexString: String)
    {

        var tosend = Array<UInt8>()
        var lenval = Array<UInt8>(repeating: 0, count: 2)
        lenval[0] = (UInt8)(length & 0xff)
        lenval[1] = (UInt8)((length >> 8) & 0xff)

        tosend.append(CMD[0])
        tosend.append(CMD[1])
        tosend.append(lenval[0])
        tosend.append(lenval[1])
}

I got output like this

[123, 115, 115, 105, 100, 58, 50, 51, 58, 52, 51, 58, 52, 53, 58, 49, 53, 44, 112, 97, 115, 115, 119, 111, 114, 100, 58, 49, 50, 51, 52, 53, 125]

But i need to get output like this

 [0x7B, 0x73, 0x73, 0x69, ......]

and finally i have to append output array to "tosend" byte array(Array).

Any idea?

shamly
  • 21
  • 4
  • 1
    Your code is correct. There is no difference between 0x7B and 123. To convert your byte array to data just initialize it using the Data initializer `Data(tosend)` – Leo Dabus May 22 '17 at 10:41
  • 1
    http://stackoverflow.com/questions/33546967/hex-string-convert-string-uint8-array-convert-string-swift-swift-2/33548238#33548238 – Leo Dabus May 22 '17 at 10:42
  • But i need to write tosend data to BLE(bluetooth device), since it accept hex format, array item should be in hex format. Am i correct? – shamly May 22 '17 at 11:11
  • What do you mean hex format? Do you need an array of strings? – Leo Dabus May 22 '17 at 11:14
  • This is what am expecting, let bytes : [UInt8] = [0xA5, 0x00, 0x16] – shamly May 22 '17 at 11:18
  • Like I said your code is correct. – Leo Dabus May 22 '17 at 11:18
  • tosend is an array of UInt8 what's wrong with it? – Leo Dabus May 22 '17 at 11:21
  • So there is no need to convert [123, 115, 115, 105, 100, 58..] to [0x7B, 0x73, 0x73, 0x69, ......] , But is the byte array ok with BLE write – shamly May 22 '17 at 11:25
  • 1
    The way you write the number (byte) decimal 123, hexa 0x7b or binary 0b01111011 in Xcode makes no difference. What matters it is your object type – Leo Dabus May 22 '17 at 11:29
  • 1
    @shamly: Try `print(123, 0x7B)` or `print(123 == 0x7B)` to convince yourself. As Leo said, 123 and 0x7B are representations of the *same number* in different number bases. – Martin R May 22 '17 at 11:37
  • https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift . This is acceptable answer. – Green Y. Feb 05 '20 at 14:20

0 Answers0