关于进制转换的一些问题

String s = "0xAA";
int ans = Integer.decode(s);
System.out.println(ans);

如果说需要将8进制数或者16进制数转成10进制,直接把数变成String传进Integer.decode就行。

public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;  //表示进制,10为10进制
        int index = 0;
        boolean negative = false;
        Integer result;

        if (nm.isEmpty())
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }

        if (nm.startsWith("-", index) || nm.startsWith("+", index))
            throw new NumberFormatException("Sign character in wrong position");

        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }

Integer.decode()的源码中可以看到,它对16进制数前的0x有一个判断。

在中间的主要代码中我发现,主要用Integer.valueOf()方法进行进制转换,前提是把数字的前缀去掉。

String s = "0xAA";
int ans = Integer.valueOf(s.substring(2),16);
System.out.println(ans);

处理字符串的一些方法总结:

s.substring(index)从index开始的子串

s.charAt(i)

Integer.decode()

Integer.valueOf()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值