Home > Blockchain >  How to convert Hex to decimal value in Java
How to convert Hex to decimal value in Java

Time:01-17

I currently have an application where I receive 2 values e.g. 0e 15 through bluetooth. I now want to display these in decimal values.

The code is as follows:


    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    public static String formatHexString(byte[] data) {
        return formatHexString(data, false);
    }

    public static String formatHexString(byte[] data, boolean addSpace) {
        if (data == null || data.length < 1)
            return null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i  ) {
            String hex = Integer.toHexString(data[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0'   hex;
            }
            sb.append(hex);
            if (addSpace)
                sb.append(" ");
            
        }
        return sb.toString().trim();
    }
    
}

How would I go about into converting this string so I can decimal values back?

CodePudding user response:

I was confused as I somehow thought bytes had to be displayed in hexadecimal value. It didn't cross my mind that I could just showcase two bytes in decimal value. Currently have what I want with the following code:

public class HexUtil {
    public static String formatDecimalString(byte[] data, boolean addSpace) {
        if (data == null || data.length < 1)
            return null;
        int negative = data[0] < 0 ? -1 : 1;
        BigInteger bigInteger = new BigInteger(negative, data);
        String decimal = bigInteger.toString();
        if(addSpace) {
            decimal = decimal.replaceAll("(.{2})", "$1 ");
        }
        return decimal;
    }
}

CodePudding user response:

You can use java.lang.Integer library's method parseInt.

simply do Integer.parseInt(hexString,16);

For more information you can refer to documentation here.

  • Related