十进制和26进制转换

十进制和26进制转换

需要对一批数据进行处理, 数据的形式可能为纯数字:121234,或者纯字母DJIEN。

需要把字母转化为数字之后进行处理。

转换分为两步:

  1. 字母转数字
  2. 数字转字母

字母转数字

// 将大写字母转换成数字 26进制
	 public  int letterToNum(String input) {
	        int returnNum = 0;
	        int index = (int) Math.pow(26,input.length()-1);
	        for (byte b : input.getBytes()) {
	            returnNum += (b - 65)*index;
	            index/=26;
	        }
	        return returnNum;
	    }

简单起见就用大写字母处理, 原理很简单对于每一个字符,直接取ascii码,然后减去65换算成对应的0-25的数,每一位再乘以对应系数(位数的幂), 比如ABC就是A*(262)+B*(261)+C*(26^0)。

数字转字母

// 将数字转换成字母
	    public String numToLetter(Integer input,int length) {
	        String rS = "";
	        int index = 1;
	        int count = 0;
	        do{
	            index = input/(int)Math.pow(26,count);
	            count++;
	        }while (index>0);
	        int remainder = input;
	        for(int i = count-2;i>=0;i--){
	            int pow = (int)Math.pow(26,i);//种子
	            index = remainder/pow;//商
	            remainder%=pow;//余数
	            rS += (char)((byte)(index)+65);
	        }
	        for(;count<=length;count++)//补位
	        {
	            rS = 'A'+rS;
	        }
	        return rS;
	    }

首先判断一下有几位,这个是根据业务稍微设置的,因为原数若为 A** 三位数,但是因为A=0,所以实际是**在转化,当转回来的时候需要补上。
然后用对应位数的商转成字母。

参考表:

ascII表

http://blog.csdn.net/yaodong_y/article/details/8115250
http://blog.csdn.net/ge_zhiqiang/article/details/7643683

posted @ 2016-11-17 11:52  NovaCN  阅读(2367)  评论(0编辑  收藏  举报