The binary conversion is a kind of data processing that is often needed, and in some classes in Java it encapsulates the method that has the transform function, this does not introduce. In fact, the conversion between the binary is through the first-place XOR or &, and then the mobile >>> way to achieve.
For example, for a decimal integer, the int integer takes up 4 bytes, and each byte is 8 bit bits, so the integer data has 32 bits. To convert an integral type to binary, you need to num=num&1 the cardinality first, and then move the 32 bit to the right >>>1 bit until the num!=0 condition is not satisfied .To convert an integral type to octal, you need to num=num&7 the cardinality first, and then move the 32 bit to the right >>>3 bit until the num!=0 condition is not satisfied .To convert an integral type to 16, you need to num=num&15 the cardinality first and then move the 32 bit right >>>4 bit until the num!=0 condition is not satisfied . An example of the conversion of a binary by a table-checking method is as follows:
Public classtobintest2{//decimal >>>>> binary Public Static voidToBin (intN) {trans (n,1,1); } //decimal >>>>> hexadecimal Public Static voidTohex (intN) {trans (n, the,4); } //decimal >>>>> octal Public Static voidTOOTC (intN) {trans (n,7,3); } //conversion process Public Static voidTransintXint Base,intoffset) { if(x==0) {System. out. Print (0); return; } Char[] CHS = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; Char[] arr =New Char[ +];//define a temporary storage container (four eight bits for an integer data) intpos = arr.length;//defines a pointer movement while(x!=0) { inttemp = x &Base; arr[--pos] =Chs[temp]; X= x >>>offset; } for(inti = pos; I <arr.length; i++) {System. out. Print (Arr[i]); } System. out. println (); } //main function test Public Static voidMain (string[] args) {intnum; Java.util.Scanner SC=NewJava.util.Scanner (System.inch); System. out. Print ("Please enter a integer number:"); Num=Sc.nextint (); ToBin (num); Tohex (num); TOOTC (num); }}
Java: Conversion in binary