Java Array Hash Code printArray(byte[] array, boolean withHash)

Here you can find the source of printArray(byte[] array, boolean withHash)

Description

print Array

License

Apache License

Declaration

public static String printArray(byte[] array, boolean withHash) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Arrays;

public class Main {
    private static final boolean IS_ARRAYS_DEBUG = Boolean.getBoolean("infinispan.arrays.debug");

    public static String printArray(byte[] array, boolean withHash) {
        if (array == null)
            return "null";

        int limit = 8;
        StringBuilder sb = new StringBuilder();
        sb.append("[B0x");
        if (array.length <= limit || IS_ARRAYS_DEBUG) {
            // Convert the entire byte array
            sb.append(toHexString(array));
            if (withHash) {
                sb.append(",h=");
                sb.append(Integer.toHexString(Arrays.hashCode(array)));
                sb.append(']');
            }/* w  w  w . ja  v a2s.c  om*/
        } else {
            // Pick the first 8 characters and convert that part
            sb.append(toHexString(array, limit));
            sb.append("..[");
            sb.append(array.length);
            if (withHash) {
                sb.append("],h=");
                sb.append(Integer.toHexString(Arrays.hashCode(array)));
            }
            sb.append(']');
        }
        return sb.toString();
    }

    public static String toHexString(byte input[]) {
        return toHexString(input, input.length);
    }

    public static String toHexString(byte input[], int limit) {
        int i = 0;
        if (input == null || input.length <= 0)
            return null;

        char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

        char[] result = new char[(input.length < limit ? input.length : limit) * 2];

        while (i < limit && i < input.length) {
            result[2 * i] = lookup[(input[i] >> 4) & 0x0F];
            result[2 * i + 1] = lookup[(input[i] & 0x0F)];
            i++;
        }
        return String.valueOf(result);
    }

    /**
     * A function that calculates hash code of a byte array based on its
     * contents but using the given size parameter as deliminator for the
     * content.
     */
    public static int hashCode(byte[] bytes, int size) {
        int contentLimit = size;
        if (size > bytes.length)
            contentLimit = bytes.length;

        int hashCode = 1;
        for (int i = 0; i < contentLimit; i++)
            hashCode = 31 * hashCode + bytes[i];

        return hashCode;
    }
}

Related

  1. hashCode(final Object[] array1)
  2. hashCode(Map a)
  3. hashCode(Object array)
  4. hashCode(Object array)
  5. hashCode(String[] names, Object[] values)