Here you can find the source of convertToUnicode(byte[] b, boolean includesNull)
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 |
Parameter | Description |
---|---|
IllegalArgumentException | if the byte array has an odd length |
public static String convertToUnicode(byte[] b, boolean includesNull)
//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); } }