十六进制转为八进制java,算法笔记_033:十六进制转八进制(Java)

packagecom.liuzhen.systemExe;importjava.util.Scanner;public classMain {//把16进制字符串转成2进制字符串

publicString getSixteenToTwo(String A){

StringBuilder result= new StringBuilder("");char[] arrayA =A.toCharArray();for(int i = 0;i < arrayA.length;i++){inttemp;if(arrayA[i] >= 'A' && arrayA[i] <= 'F'){

temp= arrayA[i] - 'A' + 10;

}elsetemp= arrayA[i] - '0';

result.append(getNumberToTwo(temp));

}

String result1=result.toString();returnresult1;

}//把一个数字0~15转换成4位2进制

public String getNumberToTwo(intn){

StringBuilder result= new StringBuilder("");for(int i = 0;i < 4;i++){int temp = n%2;

result.append(temp);

n= n/2;

}

String temp1=result.toString();

temp1=getReverseString(temp1);returntemp1;

}//把2进制字符串转成8进制字符串

publicString getTwoToEight(String A){if(A.length() % 3 == 1)

A= "00" +A;if(A.length() % 3 == 2)

A= "0" +A;char[] arrayA =A.toCharArray();

StringBuilder result= new StringBuilder("");int count = 0;int tempResult = 0;for(int i = arrayA.length-1;i >= 0;i--){int temp = arrayA[i] - '0';

tempResult+= (int) (temp*Math.pow(2, count++));if(count == 3){

count= 0;

result.append(tempResult);

tempResult= 0;

}

}

String result1=result.toString();

result1=getReverseString(result1);

result1=getNonoZeroString(result1);returnresult1;

}//反转字符串

publicString getReverseString(String A){char[] arrayA =A.toCharArray();int start = 0;int end = arrayA.length-1;while(start

arrayA[start++] =arrayA[end];

arrayA[end--] =temp;

}returnString.valueOf(arrayA);

}//去掉字符串前面的0

publicString getNonoZeroString(String A){char[] arrayA =A.toCharArray();int count = 0;for(int i = 0;i < arrayA.length;i++){if(arrayA[i] == '0')

count++;else

break;

}char[] result = new char[arrayA.length-count];for(int i = 0;i < arrayA.length-count;i++)

result[i]= arrayA[count+i];returnString.valueOf(result);

}public static voidmain(String[] args){

Main test= newMain();

Scanner in= newScanner(System.in);//System.out.println("请输入一个正整数n:");

int n =in.nextInt();

in.nextLine();//System.out.println("请输入n个十六进制数:");

String[] A = newString[n];for(int i = 0;i < n;i++){

String temp=in.nextLine();

A[i]=temp;

}

in.close();

String[] result= newString[n];for(int i = 0;i < n;i++){

result[i]=test.getTwoToEight(test.getSixteenToTwo(A[i]));

System.out.println(result[i]);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值