Java examples for java.lang:byte Array
Return the first bytes from a byte array
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; int len = 2; System.out.println(java.util.Arrays.toString(head(bytes, len))); }/* w ww .ja v a 2 s .com*/ /** * Return the first bytes from a byte array */ public static byte[] head(byte[] bytes, int len) { if (len > bytes.length) { throw new IllegalArgumentException( "Can't ask for more data than is present"); } byte[] buff = new byte[len]; System.arraycopy(bytes, 0, buff, 0, buff.length); return buff; } /** * Print a byte array as a String */ public static String toString(byte[] bytes) { StringBuilder sb = new StringBuilder(4 * bytes.length); sb.append("["); for (int i = 0; i < bytes.length; i++) { sb.append(unsignedByteToInt(bytes[i])); if (i + 1 < bytes.length) { sb.append(","); } } sb.append("]"); return sb.toString(); } /** * Convert an unsigned byte to an int */ public static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }