How to convert sequence of ASCII code into string in swift 4?

Sabs

New Member
#1
I have an sequence of ASCII codes in string format like (7297112112121326610511411610410097121). How to convert this into text format.
I tried below code :
Mã:
func convertAscii(asciiStr: String) {
    var asciiString = ""
    for asciiChar in asciiStr {
        if let number = UInt8(asciiChar, radix: 2) { // Cannot invoke initializer for type 'UInt8' with an argument list of type '(Character, radix: Int)'
            print(number)
            let character = String(describing: UnicodeScalar(number))
            asciiString.append(character)
        }
    }
}

convertAscii(asciiStr: "7297112112121326610511411610410097121")
But getting error in if let number line.
 

Admin

Administrator
Thành viên BQT
#2
As already mentioned decimal ASCII values are in range of 0-255 and can be more than 2 digits

Based on Sulthan's answer and assuming there are no characters < 32 (0x20) and > 199 (0xc7) in the text this approach checks the first character of the cropped string. If it's "1" the character is represented by 3 digits otherwise 2.

Mã:
func convertAscii(asciiStr: String) {
    var source = asciiStr

    var result = ""

    while source.count >= 2 {
        let digitsPerCharacter = source.hasPrefix("1") ? 3 : 2
        let charBytes = source.prefix(digitsPerCharacter)
        source = String(source.dropFirst(digitsPerCharacter))
        let number = Int(charBytes)!
        let character = UnicodeScalar(number)!
        result += String(character)
    }

    print(result) // "Happy Birthday"
}

convertAscii(asciiStr: "7297112112121326610511411610410097121")
 
Top