Implement a 10-to-2 or 16-to-16 conversion.

Source: Internet
Author: User
1 public class test {2 3 Public static void main (string [] ARGs) {4 system. out. println (tobinary (9); 5 system. out. println (tohex (559); 6 system. out. println (integer. tobinarystring (9); 7 system. out. println (integer. tohexstring (559); 8/* 1001 9 22f10 100111 22f */12} 13 14 public static string tobinary (int n) {15 stringbuilder temp = new stringbuilder (); 16 while (n/2> = 1 | n % 2 = 1) {// except for 2, (| n % 2 = 1) in order to add the last 0 or 117 temp. append (N % 2); 18 N = n/2; 19} 20 return temp. reverse (). tostring (); 21} 22/** 23 10 to hexadecimal: 24 divide the given decimal integer by the base number 16, and the remainder is the equivalent hexadecimal decimal digit. 25. Divide the quotient in the previous step by the base number 16, and the remainder is the low value of the equivalent hexadecimal number. 26. Repeat the previous step until the final operator equals 0. The remainder of each division is the number of users in hexadecimal notation. The remainder of the last Division is the highest bit 27 */28 public static string tohex (int n) {29: except 16 get remainder */30 stringbuilder temp = new stringbuilder (); 31 While (N/16> = 1) {32 int AA = N/16; 33 int BB = n % 16; 34 // 0123456789 10 11 12 13 14 1535 // 0123456789 a B c d e f36 string STR = ""; 37 If (BB = 10) {38 STR = "A"; 39} else if (BB = 11) {40 STR = "B "; 41} else if (BB = 12) {42 STR = "C"; 43} else if (BB = 13) {44 STR = "D "; 45} else if (BB = 14) {46 STR = "e"; 47} else if (BB = 15) {48 STR = "F "; 49} else {50 STR = BB + ""; 51} 52 temp. append (STR); 53 n = AA; 54 if (N/16 <1) {// Add the last digit 55 temp. append (n); 56} 57} 58 return temp. reverse (). tostring (); 59} 60}

 

Implement a 10-to-2 or 16-to-16 conversion.

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.