gpt4 book ai didi

swift - 十六进制字符串到文本的转换 - swift 3

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:24 24 4
gpt4 key购买 nike

我正在尝试将十六进制字符串转换为文本。

这是我的:

// Str to Hex
func strToHex(text: String) -> String {
let hexString = text.data(using: .utf8)!.map{ String(format:"%02x", $0) }.joined()

return "0x" + hexString

}

我正在尝试将刚刚创建的十六进制字符串反转回原始字符串。

所以,例如:

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 - 十六进制字符串到文本的转换 - swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com