Today, when writing a program, you need to output byte-type data in the form of a string in the binary format. You have no idea how to get started. Suddenly, I remember that the integer package class in Java has a tobinarystring (int I)In binary format (base 2) Returns the string representation of an integer parameter in the form of an unsigned integer..
Find the JAVA Source Code File Integer. Java find the method source code is as follows:
Public static string tobinarystring (int I )...{
Return tounsignedstring (I, 1 );
} Actually, tounsignedstring (I, 1) is called. The method is used to continue searching for the source code as follows:
/***//**
* Convert the integer to an unsigned number.
*/
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 ));
}
The array digits [] to be used in the method is defined as follows:
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'
}; Now, the source code has been found. Now let's start to analyze how Java class library designers implement it. Suppose we call the tounsignedstring (5, 1); method in this way. 1) Char [] Buf = new char [32]; // create a char array with a length of 32 (INT data is 32 characters in Java) and store the computed data. 2) int charpos = 32; // counter
Int Radix = 1 <shift; // pay attention to this location
1It is an integer value (32 bits) and it is moved to the left.
1The right side of the empty space is supplemented with 0, and then assigned to radix. Is the data before and after the Left Shift
1Binary table diagram:
4) int mask = Radix-1;
The key algorithms are as follows:
5) do {
6) BUF [-- charpos] = digits [I & Mask];
7) I >>> = shift;
8)} while (I! = 0 );
6) BUF [-- charpos] Because the array subscript starts from 0, the initial index is 31 (corresponding to 32nd bits in memory ). The memory representation of digits [I & Mask] is as follows:
7) I >>> = shift;
8)} while (I! = 0); // I = 2! = 0 cycles continue step 5-7 until I = 0 ends the loop so far the program is running.
9) return new string (BUF, charpos, (32-charpos); // call the constructor of the string class to create a String object of the specified character array, the program will see that the problem has been solved here, and I will not go into the following code if you are interested, you can look at the source code.
Conclusion: after studying the Java source code, I have a better understanding of the tobinarystring (int I) method. Java library designers exchange space for speed, however, it is worthwhile to think about this waste of space. Of course, this is not the only solution.