Here you can find the source of intFromHex(String hex, boolean signed)
Parameter | Description |
---|---|
hex | hex representation with following format: #xABCD... |
signed | Defines if hex should be interpreted signed. |
public static int intFromHex(String hex, boolean signed)
//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; } }