Java Array Truncate truncateHashToLong(byte[] bytes)

Here you can find the source of truncateHashToLong(byte[] bytes)

Description

Computes a truncated code from the given hash-value and returns it as long-variable.

License

Open Source License

Parameter

Parameter Description
bytes the hash-value as a byte-array

Return

truncated code as long

Declaration

public static long truncateHashToLong(byte[] bytes) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   w  w w  .j a v  a  2  s  .c om
     * Computes a truncated code from the given hash-value and returns it as long-variable.
     *
     * @param hash the hash-string
     * @return truncated code as long
     */
    public static long truncateHashToLong(String hash) {
        return truncateHashToLong(hexToBytes(hash));
    }

    /**
     * Computes a truncated code from the given hash-value and returns it as long-variable.
     *
     * @param bytes the hash-value as a byte-array
     * @return truncated code as long
     */
    public static long truncateHashToLong(byte[] bytes) {
        int offset = bytes[bytes.length - 1] & 0x0c;
        return (((long) bytes[offset]) & (0x7fl << 56)) | (((long) bytes[offset + 1]) & (0xffl << 48))
                | (((long) bytes[offset + 2]) & (0xffl << 40)) | (((long) bytes[offset + 3]) & (0xffl << 32))
                | (((long) bytes[offset + 4]) & (0xffl << 24)) | (((long) bytes[offset + 5]) & (0xffl << 16))
                | (((long) bytes[offset + 6]) & (0xffl << 8)) | (((long) bytes[offset + 7]) & 0xffl);
    }

    /**
     * Convert a string consisting of hex-numbers into an array of bytes, which contains the binary representation of
     * those hexadecimal-numbers (takes pairs of numbers, so make sure the number of characters is even).
     *
     * @param hex String of pairs of hexadecimal numbers
     * @return byte-array with the binary representation of the hex-string
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() >> 1];
        for (int i = 0; i < bytes.length; i++) {
            int baseIndex = i << 1;
            // in order to be able to parse the full range of 0x00 to 0xFF, we need a Short or Integer
            // to do the parsing, as Byte will throw an exception for values above or equal to 0x80.
            bytes[i] = (byte) Integer.parseInt(hex.substring(baseIndex, baseIndex + 2), 16);
        }
        return bytes;
    }
}

Related

  1. truncate(short[] value, int maxSize)
  2. truncateAndConvertToInt(long[] longArray)
  3. truncateBytes(byte[] inputBytes)
  4. truncateByteSegment(byte[] byteSegment, int toSize)
  5. truncateData(byte[] data, int numOfBytes)
  6. truncateI(long[] v, int len)
  7. truncateLeft(byte[] b1, int bytes)