Muthu Sabarinathan
Muthu Sabarinathan

Reputation: 1208

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

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)'
            print(number)
            let character = String(describing: UnicodeScalar(number))
            asciiString.append(character)
        }
    }
}

convertAscii(asciiStr: "7297112112121326610511411610410097121")

But getting error in if let number line.

Upvotes: 1

Views: 2324

Answers (2)

vadian
vadian

Reputation: 285069

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

Upvotes: 2

Sulthan
Sulthan

Reputation: 130092

If we consider the string to be composed of characters where every character is represented by 2 decimal letters, then something like this would work (this is just an example, not optimal).

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

    var characters: [String] = []

    let digitsPerCharacter = 2

    while source.count >= digitsPerCharacter {
        let charBytes = source.prefix(digitsPerCharacter)
        source = String(source.dropFirst(digitsPerCharacter))
        let number = Int(charBytes, radix: 10)!
        let character = UnicodeScalar(number)!
        characters.append(String(character))
    }

    let result: String = characters.joined()
    print(result)
}

convertAscii(asciiStr: "7297112112121326610511411610410097121")

However, the format itself is ambigious because ASCII characters can take from 1 to 3 decimal digits, therefore to parse correctly, you need all characters to have the same length (e.g. 1 should be 001).

Note that I am taking always the same number of letters, then convert them to a number and then create a character the number.

Upvotes: 0

Related Questions