Returns a new byte array of the specified length using the contents provided. - Java java.lang

Java examples for java.lang:byte Array

Description

Returns a new byte array of the specified length using the contents provided.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int length = 2;
        System.out.println(java.util.Arrays.toString(resize(data, length)));
    }/*from   ww w  .  j ava2  s . co m*/

    /**
     * Returns a new byte array of the specified length using the contents
     * provided. Pads and truncates as necessary.
     */
    public static byte[] resize(byte[] data, int length) {
        byte[] newArray = new byte[length];
        int copyLength = Math.min(length, data.length);
        System.arraycopy(data, 0, newArray, 0, copyLength);
        return newArray;
    }

    /**
     * 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;
    }
}

Related Tutorials