Convert a decimal to binary, octal, hexadecimal, and binary hexadecimal
Package com. db2;/*** convert a decimal to binary, octal, hexadecimal ** @ author denny **/public class Demo2 {public static void main (String [] args) {toBin (6); toBin (-6); toOct (60); toOct (-60); toHex (60); toHex (-60 );} // convert the binary public static void toBin (int num) {toTran (num, 1, 1); // 1 is the maximum value of the binary system, which is 0, 1, 1-bit right shift} // public static void toOct (int num) {toTran (num, 7, 3); // 7 is the maximum value in binary format, the maximum value of octal is 7, 3 bits, and 2 bits, indicating that octal shifts three bits to the right} // hexadecimal Public static void toHex (int num) {toTran (num, 15, 4); // 15 is the hexadecimal maximum value, the hexadecimal value is only 0-15, and the maximum value is 15. The 4-digit binary value represents an octal shift of 4 digits to the right} // Conversion Function private static void toTran (int num, int base, int offset) {// num number to be converted, sum number, right shift number char [] ch = {'0', '1', '2', '3 ', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D ', 'E', 'F'}; // The hexadecimal element contains 2, hexadecimal, octal // stores the converted data. // The maximum value is 32 characters. char [] arr = new char [32]; // defines the subscript of the control array. int pos = arr. length; // start the conversion While (num! = 0) {int temp = num & base; // With the arr [-- pos] = ch [temp]; // locate and store num = num >>> offset ;} // output for (int I = pos; I <arr. length; I ++) {System. out. print (arr [I]);} System. out. println ();}}