How to parse ascii hex equivalent string in Swift 2

In swift 2, the best way to turn strings of hexadecimal characters into their equivalent is ascii.

Considering

let str1 = "0x4d 0x4c 0x4e 0x63"
let str2 = "4d 4c 4e 63"
let str3 = "4d4c4e63"
let str4 = "4d4d 4e63"
let str5 = "4d,4c,4e,63"

we would like to run a function (or line extension) that spits out: "MLNc", which is the equivalent of ascii hexadecimal strings

Pseudocode:

  • Remove all trash, commas, etc.
  • Get "2 character fragments" and then convert these characters to the int equivalent using strtoul
  • build an array of characters and combine them into a string

Partial implementation

func hexStringtoAscii(hexString : String) -> String {

    let hexArray = split(hexString.characters) { $0 == " "}.map(String.init)
    let numArray = hexArray.map{  strtoul($0, nil, 16)  }.map{Character(UnicodeScalar(UInt32($0)))}
    return String(numArray)
}

Is this a partial implementation on the right track? And if so, how best to handle chunking

+2
source share
1

" " . , , "0x", 2 . "(0x)?([0-9a-f]{2})".

Character , , String, " ". strtoul() UInt32

init?(_ text: String, radix: Int = default)

Swift 2.

" " ( ), "0x", , rangeAtIndex(2).

, :

func hexStringtoAscii(hexString : String) -> String {

    let pattern = "(0x)?([0-9a-f]{2})"
    let regex = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
    let nsString = hexString as NSString
    let matches = regex.matchesInString(hexString, options: [], range: NSMakeRange(0, nsString.length))
    let characters = matches.map {
        Character(UnicodeScalar(UInt32(nsString.substringWithRange($0.rangeAtIndex(2)), radix: 16)!))
    }
    return String(characters)
}

(. Swift NSString.)

, , 2- , :

let str6 = "4d+-4c*/4e😈🇩🇪0x63"

Swift 3:

func hexStringtoAscii(_ hexString : String) -> String {

    let pattern = "(0x)?([0-9a-f]{2})"
    let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let nsString = hexString as NSString
    let matches = regex.matches(in: hexString, options: [], range: NSMakeRange(0, nsString.length))
    let characters = matches.map {
        Character(UnicodeScalar(UInt32(nsString.substring(with: $0.rangeAt(2)), radix: 16)!)!)
    }
    return String(characters)
}
+4

Source: https://habr.com/ru/post/1685419/


All Articles