我是靠谱客的博主 花痴蓝天,最近开发中收集的这篇文章主要介绍【Java】10进制和n进制互相转换,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

进制之间的转换,需要从最后一位入手;

① n进制 -> 10进制

基本思路:反序处理, 按位取次方求和;

② 10进制 -> n进制

基本思路:对商取余,反序处理;

可以试着分解一组10进制数字,就可以发现规律:

例:16进制数 "be6",对应的10进制为 "3046":

(需要格外注意余数 = 0的情况)
 

 

----------------------------------------------------------------------------

实际应用:

已知excel列号,获取列index:

    /**
     * get column index by column address
     */
    public static int getColumnIndexByAddress(String columnAddress) {
        int colNum = 0;

        for (int i = 0; i < columnAddress.length(); i++) {
            char ch = columnAddress.charAt(columnAddress.length() - 1 - i);
            colNum += (ch - 'A' + 1) * Math.pow(26, i);
        }

        return colNum - 1;
    }

已知列index,获取列号:

    /**
     * get column address by column index
     */
    public static String getColumnAddressByIndex(int columnIndex) {
        String colAddress = "";

        int quotient = columnIndex + 1;
        int remainder = 0;

        while (quotient > 0) {
            remainder = quotient % 26;
            if (remainder == 0) {
                colAddress += 'Z';
                quotient = quotient - 26;
            } else {
                colAddress += String.valueOf((char) (remainder - 1 + 'A'));
            }
            quotient = quotient / 26;
        }

        StringBuffer sb = new StringBuffer(colAddress);

        return sb.reverse().toString();
    }

 

最后

以上就是花痴蓝天为你收集整理的【Java】10进制和n进制互相转换的全部内容,希望文章能够帮你解决【Java】10进制和n进制互相转换所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部