amorotez
amorotez

Reputation: 33

How do I convert from ASCII to String

I am trying to parse an ascii list to a string. The problem is that with some special chars, I have torubles. If I try to parse this:

115 097 116 195 168 108 194 183 108 105 116

, the result sould be "satèl·lit". The code I am using to parse it is :

ASCIIList.add(Character.toString((char) Integer.parseInt(asciiValue)));

But the result is satèl·lit. I saw that for example "è" -> "195 168". I do not know how to parse it correctly.

Upvotes: 2

Views: 576

Answers (1)

Codo
Codo

Reputation: 78835

Assuming you already have split the input into an array of string, the code could look like so:

String convertToString(String[] numberArray) {
    byte[] utf8Bytes = new byte[numberArray.length];
    for (int i = 0; i < numberArray.length; i++) {
        utf8Bytes[i] = (byte) Integer.parseInt(numberArray[i]);
    }
    return new String(utf8Bytes, StandardCharsets.UTF_8);
}

So each number becomes a bytes. The entire array of bytes is then converted into a string using UTF-8 charset.

UTF-8 uses multiple bytes to represent characters outside the ASCII range. In your example it affects "è" and "·".

Upvotes: 5

Related Questions