Swift 2 How to encode from ASCII to Hexadecimal

蓝咒 提交于 2020-01-22 03:00:09

问题


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 change the format of my string:

StringToConvert(String(format: "%02hhx", $0))

Thanks for your help :)


回答1:


"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



回答2:


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) }


来源:https://stackoverflow.com/questions/32884783/swift-2-how-to-encode-from-ascii-to-hexadecimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!