import java.util.ArrayList;
import java.util.List;
/**
* M进制与N进制的转换
* @author Administrator
*
*/
public class Convert {
public static int M=8;
public static int N=10;
List<String> modeList = new ArrayList<String>();
String shang;//保存商
private void getMode(String number) {
shang = "";
int temp = 0;//保存余数
while(number.length()>0)
{
int n = getInt(number.substring(0, 1));
number = number.substring(1);
temp =temp*M+n;
shang +=getStr(temp/N);
System.out.println("shang="+shang);
temp = temp % N;
System.out.println("temp="+temp);
}
while (shang.length() > 0 && shang.charAt(0) == '0') {
shang = shang.substring(1);
}
/*
* 将余数加入到arrayList里面
* 2| 9-----1
* 2| 4----0
* 2| 2---0
* 2| 1--1
* 0
*/
modeList.add(getStr(temp));
//getMode的递归
while(shang.length()>0){
getMode(shang);
}
}
/**
* {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J"};
* 一一对应
* { 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 , 18,19 , 20};
* 根据字符来获取对应的整数
*/
private int getInt(String str) {
int result;
if (str.charAt(0) >= '0' && str.charAt(0) <= '9') {
result = str.charAt(0) - '0';
} else {
result = str.charAt(0) - 'A' + 10;
}
return result;
}
/**
* 通过整数来获取对应的字符
*/
private String getStr(int number)
{
String result;
if(number>=0&&number<=9) {
result = String.valueOf((char)('0'+number));
}
else if(number>=10&&number<=36){
result = String.valueOf((char)('A'+number-10));
}
else{
result = "-1";//出错了
}
return result;
}
public static void main(String [] args)
{
String result="";
Convert c = new Convert();
c.getMode("256");
//遍历arrayList
for(int i =0;i<c.modeList.size();i++)
{
//将arrayList里面的元素按照下标的降序序列组合成一个字符串。
result = c.modeList.get(i)+result;
}
System.out.println("result:"+result);
}
}
M进制与N进制之间的转换
最新推荐文章于 2021-08-18 15:48:01 发布