Java实现进制转换
进制转换基础知识可以参考我的一篇博客:<a href='https://blog.csdn.net/Honeycomb_1/article/details/104828169'></a>
以16进制转10进制为例:
方法一:十六进制先转化为二进制,然后再转化为10进制
import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String [] args){ Scanner sc = new Scanner(System.in); String str = sc.next();///输入16进制 String str1=""; StringBuilder stringBuilder = new StringBuilder(); for(int j=0;j< str.length();j++){ str1 = Integer.toBinaryString(Integer.valueOf(str.charAt(j)+"",16)); ///16进制的每一位转化为二进制 while(str1.length()<4&&j!=0) str1="0"+str1;///加0 stringBuilder.append(str1);///加入字符串容器中 } int numtmp = 0; BigInteger value = new BigInteger("0");///BigInteger包装超大数据 long valuetmp; for(int k = stringBuilder.length()-1;k>=0;k--){ valuetmp = Integer.parseInt(stringBuilder.charAt(k)+"")*(long)Math.pow(2,numtmp); ///二进制中一位位转化为十进制 value = value.add(BigInteger.valueOf(valuetmp));///a.add(b)为a+b numtmp++; } System.out.println(value); } }
方法二:直接运用java库函数转换
import java.util.Scanner; public class Main { public static void main(String [] args){ Scanner sc = new Scanner(System.in); String str = sc.next(); Long ans = Long.parseLong(str,16); System.out.println(ans); } }
反过来,以10进制转16进制为例:
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); String [] sum = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; ArrayList<String>list = new ArrayList<String>(); if(n==0) System.out.println(0); int yu; while(n!=0){ yu=n%16; n=n/16; list.add(sum[yu]); } String str=""; for(int i=list.size()-1;i>=0;i--) str+=list.get(i); System.out.println(str); } }
不忘初心,方得始终。只有走过弯路,才更确信当初最想要的是什么。