decimal to hexadecimal,binary and octonary.

Here is a simple algorithm about 'decimal' to 'dexadecimal',and the implementation code:

 1 /*
 2 Convert from decimal to binary,octonary and hexadecimal.
 3 */
 4 package kju.decto;
 5 
 6 import kju.print.Printer;
 7 public class DecimalTo {
 8     public static String decToHex(int num) {
 9         return transDec(num, 15, 4);
10     }
11 
12     public static String decToBinary(int num) {
13         return transDec(num, 1, 1);
14     }
15 
16     public static String decToOctonary(int num) {
17         return transDec(num, 7, 3);
18     }
19 
20     /*transform decimal to others.
21     num: the input decimal.
22     base: the value to be '&'(bitwise AND) operate with 'num' for each shift operation.
23     offset:the number to shift each time.
24     */
25     private static String transDec(int num, int base, int offset) {
26         if(num == 0)
27             return "0";
28         char[] csRef = getHexTable();
29         char[] csStorage = new char[32];    //store the result(32 is the max length).
30         int pos = csStorage.length;    //position to store in the 'scStorage'.
31         while(num != 0) {
32             int temp = num & base;
33             csStorage[--pos] = csRef[temp];
34             num >>>= offset;
35         }
36         return String.valueOf(csStorage, pos, csStorage.length - pos);
37     }
38     
39     //table that contains each item of hexadecimal letter.
40     private static char[] getHexTable() {
41         return new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
42     }
43 
44     public static void main(String[] args) {
45         String result = decToHex(60);
46         Printer.println(result);
47         //prints:3C.
48         Printer.printHr();
49         result = decToBinary(-6);
50         Printer.println(result);
51         //prints:11111111111111111111111111111010.
52         Printer.printHr();
53         result = decToOctonary(30);
54         Printer.println(result);
55         //prints:36
56     }
57 }

 

 Rre:  Some relevant operations.

转载于:https://www.cnblogs.com/listened/p/3579534.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值