1

I am currently writing a program that reads the ID of NFC Tags and reverses them. The thing I am trying to accomplish now is to convert that reversed ID from Hex to Dec

Let's say that the ID of the number would be "3bde4eac", so the reversed result would be "ac4edb3b"

And I don't really know how to correctly convert that HexString to Decimal.

Here is my current code:

else{
            String tagInfo = tag.toString() + "\n";

            tagInfo = "";
            byte[] tagId = tag.getId();
            for(int i=n; i<tagId.length; i++){

                tagInfo += Integer.toHexString(tagId[i] & 0xFF);

            }

            String s = tagInfo;
            StringBuilder result = new StringBuilder();
            for(int n = 0; n <=s.length()-2; n=n+2) {
                result.append(new StringBuilder(s.substring(n, n + 2)).reverse());

            }
            s = result.reverse().toString();
            Long f = Long.parseLong(s, 16);
            textViewInfo.setText(s);
        }

EDIT: Using the "duplicate link", I was able to solve the problem.

I changed the last part of my code to

s = result.reverse().toString();
            Long g = hex2decimal(s);
            textViewInfo.setText(g.toString());

With the function

public static Long hex2decimal(String s) {
    String digits = "0123456789ABCDEF";
    s = s.toUpperCase();
    long val = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        long d = digits.indexOf(c);
        val = 16*val + d;
    }
    return val;
}
Remph
  • 323
  • 1
  • 4
  • 14

1 Answers1

1

You should try parsing the reversed string as hexadecimal and then convert the obtained int value to decimal. Check out Integer.parseInt(strValue, 16) to parse String in base16/hexadecimal and Integer.toString(intValue) for this.

Alex Traud
  • 206
  • 1
  • 4
  • Integer.parseInt("ac4edb3b", 16) throws a NumberFormatException – Faruk Yazici Aug 10 '18 at 08:31
  • Looks like the value represented by specified string in hexadecimal does not fit into an (unsigned) `int` (I guess the maximum is `Integer.MAX_VALUE` or `0x7fffffff`. Options are: use `Long.parseLong(s, 16)` or `new BigInteger(s, 16)` for even larger numbers. – Alex Traud Aug 13 '18 at 06:52