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


New Member
I have an sequence of ASCII codes in string format like (7297112112121326610511411610410097121). How to convert this into text format.
I tried below code :
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)'
            let character = String(describing: UnicodeScalar(number))

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


Thành viên BQT
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.

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

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.