Thought: Decimal to hexadecimal, only need to num&15 the decimal number, then num to right four bits (NUM>>>4), here using the table method, that is, ' 0 '-' F ' in the array chs, and then will chs[num&15] The value of blessing encounters a new array in arr or in container stringbuffer. The tabular method can be used to request hexadecimal for negative numbers.
Essence: First "and" then "move".
Class Tohex{public static void Main (string[] args) {Tohex_array (-60);//Check table method can be used for negative numbers to find its hexadecimal. System.out.println ("Hello world!");} Non-check table method (the most common method). The emphasis is on/*temp=num&15;if (temp>9) sb.append ((char) (temp-10+ ' A ')); Elsesb.append (temp); num=num>>>4;*/ public static void Tohex (int num) {stringbuffer sb=new stringbuffer (), int temp, for (int i=0;i<8;i++) {//Turn to 8-bit hex temp=n Um&15;if (temp>9) sb.append ((char) (temp-10+ ' A ')); Elsesb.append (temp); num=num>>>4;} System.out.print (Sb.reverse ());} /*********************** The following two methods are used to realize the conversion of the ******************************///with the table method StringBuffer to store public static void tohex_table (int num) {char[] chs={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '} ;//Note to start with ' 0 '!! This will satisfy the chs[1]= ' 1 '. StringBuffer sb=new StringBuffer (); for (int i=0;i<8;i++) {int temp=num&15;//system.out.print (chs[temp]); Sb.append (Chs[temp]); num=num>>>4;} System.out.print (Sb.reverse ());} Use an array to store public static void Tohex_array (int num) {char[] chs={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};//note to start with ' 0 '!! This will satisfy the chs[1]= ' 1 '. Char[] arr=new char[8];int i=arr.length;while (num!=0) {int temp=num&15;arr[--i]=chs[temp];num=num>>>4;} for (int j=i;j<arr.length;j++) System.out.print (Arr[j]);}}
java-Decimal Turn hex