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

时间:2017-03-12 21:07:40

标签: swift string text hex

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

这就是我所拥有的:

// 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"
有人能帮帮我吗? 谢谢

2 个答案:

答案 0 :(得分:5)

你可能会使用这样的东西:

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

答案 1 :(得分:1)

NSRegularExpression对这份工作来说太过分了。您可以通过一次抓取两个字符将字符串转换为字节数组:

func hexToString(hex: String) -> String? {
    guard hex.characters.count % 2 == 0 else {
        return nil
    }

    var bytes = [CChar]()

    var startIndex = hex.index(hex.startIndex, offsetBy: 2)
    while startIndex < hex.endIndex {
        let endIndex = hex.index(startIndex, offsetBy: 2)
        let substr = hex[startIndex..<endIndex]

        if let byte = Int8(substr, radix: 16) {
            bytes.append(byte)
        } else {
            return nil
        }

        startIndex = endIndex
    }

    bytes.append(0)     
    return String(cString: bytes)
}