Write a function trans ();
1 Decimal to binary binary
2 ability to decimal to octal
3 ability to decimal to hexadecimal
4 Package functions
Code implementation:
Class Arrarytest {public static void main (string[] args) {int num=60; String str_bin=tobinary (num); String str_oct=tooctal (num); String Str_hex=tohex (num); System.out.println ("Self-defined conversions"); System.out.println ("Bin:" +str_bin); System.out.println ("Oct:" +str_oct); System.out.println ("Hex:" +str_hex); SYSTEM.OUT.PRINTLN ("System comes with the conversion"); System.out.println (integer.tobinarystring (60)); System.out.println (integer.tooctalstring (60)); System.out.println (integer.tohexstring (60));} Decimal to hexadecimal public static String tohex (int num) {return "0x" +trans (num,15,4);} Decimal to binary public static String tobinary (int num) {return trans (num,1,1);} Decimal to octal public static String tooctal (int num) {return "0" +trans (num,7,3);} Call the trans function to convert public static String trans (int num,int base,int offset) {///base bitwise with the number of offset right shift number if (num==0) return "0 "; Hit table completion conversion char []chs={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};char []arr=new char[32]; int index=arr.length;///specific operation while (num!=0) {int Temp=num&base;arr[--index]=chs[temp];num=num>>>offset;} Return toString (Arr,index);} Numeric to String function public static string toString (char []arr,int POS) {String temp= "", for (int i=pos;i<arr.length;++i) {temp+= Arr[i];} return temp;}}
Operation Result:
My first Java program feels okay.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JAVA Learning-in-the-process transformation