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