Java Hex to Int convertHexBytesToInt(byte[] hex)

Here you can find the source of convertHexBytesToInt(byte[] hex)

Description

convert Hex Bytes To Int

License

Open Source License

Declaration

public static int convertHexBytesToInt(byte[] hex) 

Method Source Code

//package com.java2s;

public class Main {
    public static int convertHexBytesToInt(byte[] hex) {
        String hexString = stringify_nospaces(hex);
        String asciiString = convertHexToString(hexString);
        return convertHexStringToInt(asciiString);
    }//from   ww  w . j  ava  2s  .  co m

    static public String stringify_nospaces(byte[] bytes) {
        final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

        if (bytes == null)
            return null;

        if (bytes.length == 0)
            return "";

        StringBuilder s = new StringBuilder(bytes.length << 1);

        for (byte b : bytes) {
            s.append(hexChars[(b & 0xF0) >> 4]);
            s.append(hexChars[b & 0x0F]);
        }

        return s.toString();
    }

    /**
     *
     * @param hex
     *            49204c6f7665204a617661
     * @return I Love Java
     */
    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            // grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            // convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            // convert the decimal to character
            sb.append((char) decimal);
        }
        return sb.toString();
    }

    /**
     *
     * @param hex
     *            31 30
     * @return 16
     */
    public static int convertHexStringToInt(String hex) {
        return Integer.valueOf(hex, 16);
    }
}

Related

  1. convertHexDigitAsInt(char c)
  2. convertHexStringToInt(String hex)
  3. convertHexStringToInt(String hexString)
  4. convertHexToDec(String in)