赞
踩
今天教大家使用代码如何完成十进制对二进制、八进制、十六进制的转换。
我们直接上代码↓↓↓
//十进制转换为二进制 public static void main(String[] args) { System.out.println("请输入一个数:"); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); toBin1(x); } //功能实现函数 public static void toBin1(iny num){ StringBuffer sb = new StringBuffer(); while(num>0) { sb.append(num%2); num = num /2; } System.out.println2(sb.reverse()); } //使用查表法进行转换函数 public static void toBin(iny num){ char[] chs={'0','1'} char[] arr = new char[32]; int pos = arr.length; while(num 1= 0){ int temp = num & 1; arr[--pos] = chs[temp]; num = num>>>1; } for(int x = pos;x<arr.length;x++){ System.out.println(arr[x]); } }
十进制转换十六进制
public static void main(String[] args) { System.out.println("请输入一个数:"); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); toHex(x); } //第一种转换方式实现的函数 public static void toHex(iny num){ StringBuffer sb = new StringBuffer(); for(int x = 0;x<8;x++){ int temp = num & 15; if(temp > 9) { sb.append((char)(temp-10+'A')); }else { sb.append(temp) } num = num >>>4; } System.out.println(sb.reverse()); } //第二种(查表法)实现转换功能: public static void toHex(iny num){ char[] chs={'1','2','3' ,'4','5','6','7' ,'8','9','A','B' ,'C','D','E','F'} char[] arr = new char[8]; int pos = arr.length; while(num != 0){ int temp = num & 15; arr[--pos] = chs[temp]; num = num>>>4; } System.out.println("pos="+pos); for(int x= pos;x<arr.length;x++){ System.out.println(arr[x]+","); } }
十进制转二进制、八进制、十六进制
//10-->2 public static void toBin(int num){ trans(num,1,1); } //10-->8 public static void toBa(int num){ trans(num,7,3); } //10-->16 public static void toBin(int num){ trans(num,15,4); } //实现转换功能函数(查表法) public static void trans(int num,int base,int offset){ if(num == 0){ System.out.println(0); return; } char[] chs = {'1','2','3' ,'4','5','6','7' ,'8','9','A','B' ,'C','D','E','F'} char[] arr = new char[32]; int pos = arr.length; while(num != 0){ int temp = num & base; arr[--pos] = chs[temp]; num = num>>>offset; } for(int x= pos;x<arr.length;x++){ System.out.println(arr[x]); } }
Perfact ؏؏☝ᖗ乛◡乛ᖘ☝؏؏
所有的进制转换都实现啦,现在可以直接拿去使用啦!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。