Java examples for java.lang:byte Array Convert
Converts a 16-bit unsigned int to a 2-byte array
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { int value = 2; System.out.println(java.util.Arrays.toString(fromUInt16(value))); }/* w w w. ja v a2s . c o m*/ /** * Converts a 16-bit unsigned int to a 2-byte array */ public static byte[] fromUInt16(int value) { if (value < 0) { throw new IllegalArgumentException( "Must be less greater than 0"); } if (value > 65355) { throw new IllegalArgumentException("Must be less than 2^32"); } byte[] bytes = new byte[2]; bytes[0] = (byte) ((value >>> 8) & 0xFF); bytes[1] = (byte) (value & 0xFF); return bytes; } /** * 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; } }