Java Integer From intFromHex(String hex, boolean signed)

Here you can find the source of intFromHex(String hex, boolean signed)

Description

Converts a hex representation (hexadecimal two's complement) of an integer to an integer.

License

Open Source License

Parameter

Parameter Description
hex hex representation with following format: #xABCD...
signed Defines if hex should be interpreted signed.

Return

converted number

Declaration

public static int intFromHex(String hex, boolean signed) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w  ww  . j  av a  2  s.c o m
     * Converts a hex representation (hexadecimal two's complement) of an integer to an integer.
     *
     * @param hex hex representation with following format: #xABCD...
     * @param signed Defines if {@code hex} should be interpreted signed.
     * @return converted number
     */
    public static int intFromHex(String hex, boolean signed) {
        if (hex == null || !hex.matches("\\#x[a-fA-F0-9]+")) {
            throw new IllegalArgumentException("hex does not match expected format");
        }
        hex = hex.substring(2);
        int result = 0;
        for (int i = 0; i < hex.length(); i++) {
            result *= 16;
            result += Integer.parseInt(hex.charAt(i) + "", 16);
        }
        int full = ((int) Math.pow(16, hex.length()));
        if (result >= full / 2 && signed) {
            result = -(full - result);
        }
        return result;
    }
}

Related

  1. intFromBytes(byte[] buffer, int offset)
  2. intFromBytes(byte[] bytes)
  3. intFromBytes(byte[] bytes)
  4. intFromBytes(byte[] bytes, int offset)
  5. intFromByteWithoutStupidJavaSignExtension(byte val)
  6. intFromJSON(String[] json, int pos)
  7. intFromLex(byte[] bytes)
  8. IntFromRGB(int r, int g, int b)
  9. intFromString(String str, int dflt)