Convert integer source code to binary to hexadecimal

Source: Internet
Author: User


There is a private method, where tounsignedstring (int I, int shift) is
Public static string tohexstring (int I ){
Return tounsignedstring (I, 4 );
}
Public static string tobinarystring (int I ){
Return tounsignedstring (I, 1 );
}
Two methods are provided.

final static char[] digits = {        '0' , '1' , '2' , '3' , '4' , '5' ,        '6' , '7' , '8' , '9' , 'a' , 'b' ,        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,        'o' , 'p' , 'q' , 'r' , 's' , 't' ,        'u' , 'v' , 'w' , 'x' , 'y' , 'z'    }; private static String toUnsignedString(int i, int shift) {        char[] buf = new char[32];        int charPos = 32;        int radix = 1 << shift;        int mask = radix - 1;        do {            buf[--charPos] = digits[i & mask];            i >>>= shift;        } while (i != 0);        return new String(buf, charPos, (32 - charPos));    }
For example, convert 559 to hexadecimal:

559 binary bits 10 0010 1111;

Tounsignedstring (I, 4 );
1. Take the hexadecimal character corresponding to the 4-digit calculation;
2. Move four places to the right and add 0 to the front;
Repeat 1, 2;
----------
Mask = 15, corresponding to 1111;

10 0010 1111 & Mask = 1111-> 15-> digits [15]-> F;
Shift four digits right after 00 0010 0010 & Mask = 0010-> 2-> digits [2]-> 2;
Shift four digits right after 00 0000 0010 & Mask = 0010-> 2-> digits [2]-> 2;

----> 22f

Similarly, if it is converted to an octal format, it is: tounsignedstring (I, 3 );

I feel that all my algorithms are weak.

Convert integer source code to binary to hexadecimal

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.