Swift 2 How to encode from ASCII to Hexadecimal

前端 未结 2 940
广开言路
广开言路 2021-01-25 22:12

I have a simple ASCII string and i want to convert it to hexadecimal (base16). I\'m using xCode 7 (so i\'m on IOS9) but i can\'t find any solution anywhere.

I tried to c

相关标签:
2条回答
  • 2021-01-25 22:26

    Great answer above. Just for clarification, it's implemented like this:

    let hexRepresentation = myASCIIString.utf8.map{ $0 }.reduce("") { $0 + String($1, radix: 16, uppercase: false) }
    
    0 讨论(0)
  • 2021-01-25 22:34
    "abcdefghijklmnopqrstuvwxyz0123456789".utf8.map{ $0 }.reduce("") {
        $0 + String($1, radix: 16, uppercase: false)
    }
    

    modify it by your needs

    "ABCD".utf8.map{ $0 }.reduce("") {
        $0 + "0x" + String($1, radix: 16, uppercase: false) + " "
    }
    // 0x41 0x42 0x43 0x44
    
    0 讨论(0)
提交回复
热议问题