十六进制字符串到文本的转换 - swift 3 [英] Hex string to text conversion - swift 3
本文介绍了十六进制字符串到文本的转换 - swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将十六进制字符串转换为文本.
I'm trying to convert an hex string to text.
这就是我所拥有的:
// Str to Hex
func strToHex(text: String) -> String {
let hexString = text.data(using: .utf8)!.map{ String(format:"%02x", $0) }.joined()
return "0x" + hexString
}
我正在尝试将刚刚创建的十六进制字符串反转回原始字符串.
and I'm trying to reverse the hex string that I've just created back to the original one.
例如:
let foo: String = strToHex(text: "K8") //output: "0x4b38"
我想做类似的事情
let bar: String = hexToStr(hex: "0x4b38") //output: "K8"
有人可以帮我吗?谢谢
推荐答案
你可能可以这样使用:
func hexToStr(text: String) -> String {
let regex = try! NSRegularExpression(pattern: "(0x)?([0-9A-Fa-f]{2})", options: .caseInsensitive)
let textNS = text as NSString
let matchesArray = regex.matches(in: textNS as String, options: [], range: NSMakeRange(0, textNS.length))
let characters = matchesArray.map {
Character(UnicodeScalar(UInt32(textNS.substring(with: $0.rangeAt(2)), radix: 16)!)!)
}
return String(characters)
}
这篇关于十六进制字符串到文本的转换 - swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文