Convert a decimal to binary, octal, hexadecimal, and binary hexadecimal

Source: Internet
Author: User

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 ();}}

 

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.