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.

你可能感兴趣的:(binary)