Java String Truncate truncateHashToInt(String hash)

Here you can find the source of truncateHashToInt(String hash)

Description

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

License

Open Source License

Parameter

Parameter Description
hash the hash-string

Return

truncated code as int

Declaration

public static int truncateHashToInt(String hash) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   w w  w.ja  v a2 s  .  com
     * Computes a truncated code from the given hash-value and returns it as int-variable.
     *
     * @param hash the hash-string
     * @return truncated code as int
     */
    public static int truncateHashToInt(String hash) {
        return truncateHashToInt(hexToBytes(hash));
    }

    /**
     * Computes a truncated code from the given hash-value and returns it as int-variable.
     *
     * @param bytes hash-value as a byte-array
     * @return truncated code as int
     */
    public static int truncateHashToInt(byte[] bytes) {
        int offset = bytes[bytes.length - 1] & 0x0f;
        return (bytes[offset] & (0x7f << 24)) | (bytes[offset + 1] & (0xff << 16))
                | (bytes[offset + 2] & (0xff << 8)) | (bytes[offset + 3] & 0xff);
    }

    /**
     * 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. truncatedStr(String s, int maxLength)
  2. truncateExtension(String name)
  3. truncateFileName(String agent, String s)
  4. truncateFileType(String p)
  5. truncateFirstEnd(String str)
  6. truncateIfTooLong(String string, int maxLength)
  7. truncateIgnoreCase(String aString, String trailingSubString)
  8. truncateInt(String intStr)
  9. truncateJavaBeanMethodName(String methodName, int prefixLength)