int类型的数据有32位,16进制用4位二进制表示一位。用int的二进制数依次 & 15 ,结果倒序就是16进制数,如图。
代码如下:
public static void main(String[] args) { toHex(60); } static void toHex(int num) { // 查表法 进制转换 // 创建16进制对应的数字表 char[] chs = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // 用8位数组来依次接收转换后的16进制的各位数 // 比如:60 & 15,那么数组第一位是C,第二位是3,其他位是 空格 (Unicode码字符:\u0000) char[] arr = new char[8]; int i = 0; while (num != 0) { int temp = num & 15; arr[i++] = chs[temp - 1]; num = num >>> 4; } for (int x = 0; x < arr.length; x++) { System.out.print(arr[x] + ","); } }
运行结果:
C,3, , , , , , ,
可见,是倒着打印,且还有很多空位,那么如何解决?
1、将temp往arr数组里传时,就倒着传,即先传第8位C,再传第7位3,剩下的就都是
输出结果是:
, , , , , ,3,C,
2、输出,从有效位开始打印
3,C ,
优化后的代码:
package com.copy; /** * * purpose :查表法 十进制转十六进制、八进制、二进制 * * @author Asin * */ public class CopyOfTest13 { public static void main(String[] args) { toHex(60); } static void toHex(int num) { // 查表法 进制转换 // 创建16进制对应的数字表 char[] chs = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // 用8位数组来依次接收转换后的16进制的各位数 // 比如:60 & 15,那么数组第一位是C,第二位是3,其他位是 空格 (Unicode码字符:\u0000) char[] arr = new char[8]; int pos = arr.length; while (num != 0) { int temp = num & 15; //1、将temp往arr数组里传时,就倒着传,即先传第8位C,再传第7位3,剩下的就都是空格 arr[--pos] = chs[temp - 1]; //无符号右移4位,这样即使传入的是负数,也可以转换 num = num >>> 4; } // 2、输出,从有效位开始打印 for (int x = pos; x < arr.length; x++) { System.out.print(arr[x] + ","); } } }
类似的:
static void toOctal(int num) { // 查表法 进制转换 // 创建8进制对应的数字表 char[] chs = { '1', '2', '3', '4', '5', '6', '7', '8' }; // 用8位数组来依次接收转换后的8进制的各位数 // 比如:60 & 7,那么数组第一位是4,第二位是7,其他位是 空格 (Unicode码字符:\u0000) char[] arr = new char[8]; int pos = arr.length; while (num != 0) { int temp = num & 7; // 1、将temp往arr数组里传时,就倒着传,即先传第8位4,再传第7位7,剩下的就都是空格 arr[--pos] = chs[temp - 1]; //右移3位 num = num >>> 3; } // 2、输出,从有效位开始打印 for (int x =pos; x < arr.length; x++) { System.out.print(arr[x] + ","); } }
提取共同部分成为一个方法。
package com.copy; /** * * purpose :查表法 十进制转十六进制、八进制、二进制 * * @author Asin * */ public class CopyOfTest13 { public static void main(String[] args) { toHex(60); toOctal(60); toBinary(6); } //转成二进制 static void toBinary(int num) { trans(num, 1, 1); } //转成八进制 static void toOctal(int num) { trans(num, 7, 3); } //转成十六进制 static void toHex(int num) { trans(num, 15, 4); } static void trans(int num, int base, int offSet) { // 比之前多了个 0 //字母不区分大小写 char[] chs = { '0','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 & base; //因为多了个0,所以temp不减一了 arr[--pos] = chs[temp]; num = num >>> offSet; } for (int x = pos; x < arr.length; x++) { // 把 【+ "," 】部分去掉,打印的直接就是对应的进制数 System.out.print(arr[x] + ","); } System.out.println(); } }
打印结果: