Rj19
Rj19

Reputation: 353

how can I flip a hex string in iOS swift

I have a hex string : 81 61 08 0a a0 80 04

now I want to reverse it like : 04 80 a0 0a 08 61 81

I have tried converting hex to number and then reversing it and convert back to hex but it doesn't provide the required result.

Upvotes: 0

Views: 394

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236370

You can simply split your collection String if the character isWhitespace, reverse it and join it back to a String:

let hex = "81 61 08 0a a0 80 04"
let hexReversed = hex.split(whereSeparator: \.isWhitespace)
                      .reversed()
                      .joined(separator: " ")
print(hexReversed)   // "04 80 a0 0a 08 61 81\n"

Upvotes: 3

Related Questions