user3824100 user3824100 - 1 month ago 16
Java Question

Convert byte[] to char[]. The encoding is UTF-16

I need to convert byte[] to char[] in Java.
The Unicode encoding used is UTF-16.

To be concise, I need a Java equivalent of c#'s UnicodeEncoding.Unicode.GetChars

Answer

C# API:

public virtual char[] GetChars(byte[] bytes);

public virtual char[] GetChars(byte[] bytes, int index, int count);

Java:

byte[] byte = ...

char[] char = new String(b, "UTF-16").toCharArray();

Java methods to return char[] :

public static char[] getCharsFromBytes(byte[] bytes, String type) {
    try {
        String byteConvert = new String(bytes, "UTF-16");
        return byteConvert.toCharArray();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DataTypeUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}


public static char[] getCharsFromBytes(byte[] bytes, int index, int count) {
    char[] charArr = getCharsFromBytes(bytes);
    char[] result = new char[count];
    for (int i = 0; i < count; i++) {
        result[i] = charArr[i + startIndex];
    }
    return result;
}
Comments