10进制转任意进制,任意进制转10进制

系统需要实现任意10进制和任意进制之间的转化(36进制以内),任意进制转化为10进制 10进制转换为任意进制

package com.myhexin.bootdemo.level3;

import java.util.Stack;

/**
 * 进制数字转化
 *
 * @author qiaolei
 * @date 2022/09/16
 */
public class SwitchNumber {
    public static void main(String[] args) {
        int src = 100;
        int toBase = 36;
        String outPutStr = "";
        outPutStr = Base10ToBaseN(src, toBase, outPutStr);
        ;

        System.out.println(outPutStr);
        int outPutStr2=0;
        outPutStr2=BaseNtoBase10("1A1",36);
        System.out.println(outPutStr2);
    }

    public static String Base10ToBaseN(int src, int toBase, String outPutStr) {
        String chs = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuffer sb = new StringBuffer();
        String digths = chs.substring(0, toBase);
        Stack s = new Stack<>();
        while (src != 0) {
            s.push(digths.charAt(src % toBase));
            src /= toBase;
        }
        while (!s.isEmpty()) {

            sb.append(s.pop());

        }
        outPutStr = sb.toString();
        return outPutStr;
    }

    /**
     * n进制转化为10进制
     *
     * @param planstr n 进制字符串
     * @return iBase 表示几进制
     */

    public static int BaseNtoBase10(String planstr, int iBase) {
        int outPutStr = 0;
        int temp = 0;
        int d;
        int p = 0;
        char c;
        int length = planstr.length();
        for (int i = 0; i < length; i++) {
            c = planstr.charAt(i);
            //将数字转化为对应的数字
            if (c >= 'A' && c <= 'Z') {
                d = c - 55;
            } else if (c >= 'a' && c <= 'Z') {
                d = c - 87;
            } else {
                d = c - 48;
            }

            //当前位权

            p = length - 1 - i;
            //0^0=1
            if (d != 0) {
                temp += d * (int) Math.pow(iBase, p);
            }
        }
        outPutStr = temp;
        return outPutStr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值