Android Unicode Convert convertToUnicode(byte[] b, boolean includesNull)

Here you can find the source of convertToUnicode(byte[] b, boolean includesNull)

Description

Converts the byte array provided to a unicode string.

License

Open Source License

Parameter

Parameter Description
b the byte array to convert to a string
includesNull determine if the byte string provided contains the UNICODE null character at the end or not; if it does, it will be removed

Exception

Parameter Description
IllegalArgumentException if the byte array has an odd length

Return

a Unicode string

Declaration

public static String convertToUnicode(byte[] b, boolean includesNull) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from ww  w .  j  av  a  2 s.  c om
     * Converts the byte array provided to a unicode string.
     * @param b the byte array to convert to a string
     * @param includesNull determine if the byte string provided contains the
     *        UNICODE null character at the end or not; if it does, it will be
     *        removed
     * @return a Unicode string
     * @throws IllegalArgumentException if the byte array has an odd length
     */
    public static String convertToUnicode(byte[] b, boolean includesNull) {
        if (b == null || b.length == 0) {
            return null;
        }
        int arrayLength = b.length;
        if (!((arrayLength % 2) == 0)) {
            throw new IllegalArgumentException(
                    "Byte array not of a valid form");
        }
        arrayLength = (arrayLength >> 1);
        if (includesNull) {
            arrayLength -= 1;
        }

        char[] c = new char[arrayLength];
        for (int i = 0; i < arrayLength; i++) {
            int upper = b[2 * i];
            int lower = b[(2 * i) + 1];
            if (upper < 0) {
                upper += 256;
            }
            if (lower < 0) {
                lower += 256;
            }
            // If upper and lower both equal 0, it should be the end of string.
            // Ignore left bytes from array to avoid potential issues
            if (upper == 0 && lower == 0) {
                return new String(c, 0, i);
            }

            c[i] = (char) ((upper << 8) | lower);
        }

        return new String(c);
    }
}

Related

  1. getEncodedSize(String value)
  2. halfWidthToFullWidth(String s)
  3. bytes2StringUNICODE(byte[] buf, int offset, int length, boolean bigEndian)
  4. asciiToBCD(byte[] ascii_buf, int asc_offset, byte[] bcd_buf, int bcd_offset, int conv_len, int type)
  5. convertToUnicodeByteArray(String s)
  6. stringToUnicode(String strText)
  7. unicode2han3last_direct(Character c)
  8. unicode2han_str(String str)
  9. unicodeEscape(String s)