0

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.

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Rj19
  • 305
  • 1
  • 6
  • 20

1 Answers1

3

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • https://stackoverflow.com/a/48089097/2303865 just add this extension to your project and `let hexReversed = hex.groups(of: 2).reversed().joined()` – Leo Dabus Jan 20 '20 at 13:25
  • but its making array not string – Rj19 Jan 20 '20 at 13:30
  • @Rj19 Are you sure? https://www.dropbox.com/s/67uddi8acb5g2tg/groupsOfTwo.jpg?dl=1 – Leo Dabus Jan 20 '20 at 13:32
  • well, just for discussion... I was wondering to handle it using bitwise operator as c language. Isn't it ?? – Rj19 Jan 20 '20 at 13:42
  • @Rj19 I have no c language knowledge. I don't know what you mean by using bitwise operator. Show your original code I can try to translate it to Swift – Leo Dabus Jan 20 '20 at 13:44