首页 > 解决方案 > 将反转的十六进制字符串转换为十进制

问题描述

我目前正在编写一个程序来读取 NFC 标签的 ID 并反转它们。我现在要完成的事情是将反转的 ID 从 Hex 转换为 Dec

假设该号码的 ID 为“3bde4eac”,则反转结果为“ac4edb3b”

而且我真的不知道如何正确地将 HexString 转换为十进制。

这是我当前的代码:

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);
        }

编辑:使用“重复链接”,我能够解决问题。

我将代码的最后一部分更改为

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

带功能

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;
}

标签: javaandroidnfc

解决方案


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.


推荐阅读