Java tutorial
//package com.java2s; public class Main { public static String[] toStringA(byte[] data) { // Advanced Technique: Extract the String array's length // from the first four bytes in the char array, and then // read the int array denoting the String lengths, and // then read the Strings. // ---------- if (data == null || data.length < 4) return null; // ---------- byte[] bBuff = new byte[4]; // Buffer // ----- System.arraycopy(data, 0, bBuff, 0, 4); int saLen = toInt(bBuff); if (data.length < (4 + (saLen * 4))) return null; // ----- bBuff = new byte[saLen * 4]; System.arraycopy(data, 4, bBuff, 0, bBuff.length); int[] sLens = toIntA(bBuff); if (sLens == null) return null; // ---------- String[] strs = new String[saLen]; for (int i = 0, dataPos = 4 + (saLen * 4); i < saLen; i++) { if (sLens[i] > 0) { if (data.length >= (dataPos + sLens[i])) { bBuff = new byte[sLens[i]]; System.arraycopy(data, dataPos, bBuff, 0, sLens[i]); dataPos += sLens[i]; strs[i] = toString(bBuff); } else return null; } } // ---------- return strs; } public static int toInt(byte[] data) { if (data == null || data.length != 4) return 0x0; // ---------- return (int) ( // NOTE: type cast not necessary for int (0xff & data[0]) << 24 | (0xff & data[1]) << 16 | (0xff & data[2]) << 8 | (0xff & data[3]) << 0); } public static int[] toIntA(byte[] data) { if (data == null || data.length % 4 != 0) return null; // ---------- int[] ints = new int[data.length / 4]; for (int i = 0; i < ints.length; i++) ints[i] = toInt(new byte[] { data[(i * 4)], data[(i * 4) + 1], data[(i * 4) + 2], data[(i * 4) + 3], }); return ints; } public static String toString(byte[] data) { return (data == null) ? null : new String(data).trim(); } }