Decimal to binary, octal, and hexadecimal strings.

Source: Internet
Author: User

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}


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.