Decimal to binary, octal, and hexadecimal strings.
This is my own code and I hope to point out some problems. No problem. I hope to boast a few comments. I will continue to work hard, haha.
Decimal to binary
1 class DecToBin 2 {3 public static void main (String [] args) 4 {5 // System. out. println ("Hello World! "); 6 long dec =-9223372042554775807l; 7 //-9223372036854775808 is not supported. Do not try it. 8 8 String binStr =" "; 9 long decAbs = Math. abs (dec); 10 while (decAbs> 0) 11 {binStr = (decAbs & 1) + binStr; 12 decAbs >>=1; 13} 14 binStr = dec <0? "-" + BinStr: dec = 0? "0": binStr; 15 16 System. out. println (binStr); 17} 18}
Decimal to octal
1 class DecToOct 2 {3 public static void main (String [] args) 4 {5 // System. out. println ("Hello World! "); 6 long dec =-0; // is there-0? 7 String octStr = ""; 8 long decAbs = Math. abs (dec); 9 while (decAbs> 0) 10 {octStr = (decAbs & 7) + octStr; // 11 decAbs >>>= 3; 12} 13 octStr = dec <0? "-" + OctStr: dec = 0? "0": octStr; 14 System. out. println (octStr); 15} 16}
Convert decimal to hexadecimal
1 class DecToHex 2 {3 public static void main (String [] args) 4 {5 System. out. println ("Hello World! "); 6 long dec =-1; // The negative number of the calculator won't get -. -7 String hexStr = ""; 8 9 long decAbs = Math. abs (dec); 10 while (decAbs> 0) 11 {long lastFour = decAbs & 15; 12 if (lastFour> 9) 13 hexStr = (char) ('A' + lastFour-10) + hexStr; 14 else hexStr = lastFour + hexStr; 15 decAbs >>=4; 16} 17 18 hexStr = dec <0? "-" + HexStr: dec = 0? "0": hexStr; 19 System. out. println (hexStr); 20} 21}