Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex string to text conversion - swift 3

I'm trying to convert an hex string to text.

This is what i have:

// 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.

So, for example:

let foo: String = strToHex(text: "K8") //output: "0x4b38"

and i would like to do something like

let bar: String = hexToStr(hex: "0x4b38") //output: "K8"

can someone help me? Thank you

like image 390
nsollazzo Avatar asked Jan 04 '23 08:01

nsollazzo


1 Answers

You probably can use something like this:

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)
}
like image 150
Alexandre Lara Avatar answered Jan 11 '23 21:01

Alexandre Lara