pixel
pixel

Reputation: 26473

Convert ArrayList with Integes to UTF-16 String

I have an array list which contains integer values.

It looks like 83 0 97 0 109 0 112 0 108 0 101 0.

And I know that it's UTF-16 encoding.

So I would like to transform it into String Sample

Currently when I omit empty values and for remaining I use:

String.valueOf(Character.toChars(codePoint));

this results in incorrect encoding for non-english letters.

Does anyone knows how to convert such ArrayList into proper UTF-16 String?

Upvotes: 0

Views: 385

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109567

public String fromUTF16LE(int... bytes) {
    byte[] b = new byte[bytes.length];
    for (int i = 0; i < b.length; ++) {
        b[i] = (byte) bytes[i];
    }
    return new String(b, StandardCharsets.UTF_16LE);
}

Evidently the integers are bytes, in little endian order for UTF-16. One might check that the size is even. A Decoder might be used for error handling.

Upvotes: 3

Related Questions