Recently looked at the study materials, the sense of conversion is actually very interesting, especially for negative this aspect.
Below to share with you, here only write decimal to binary conversion, in fact, are the same truth
1 Public classTest1 {2 3 Public Static voidMain (string[] args) {4ToBin (-4);5ToBin (4);6 }7 /*8 * Function Name: ToBin9 * Function Description: Used to convert positive or negative numbers into binary numbersTen * Person created: ZX One * return value: void A * */ - Public Static voidToBin (intnum) { - //defines a string that is used to store the computed binary data theStringBuffer sb=NewStringBuffer (); - while(num!=0){ - //to add a computed binary number to a string - //Note: The use of & operations here, do not understand the reader, you can find on the Internet +Sb.append (num&1); - //unsigned bit operations on NUM, similar to the 2 operation, require the reader to find the exact difference +Num=num >>> 1; A } at //outputs the string in reverse order, - System.out.println (Sb.reverse ()); - } - -}View Code
If you want to write a 8-binary conversion, you can change the two statements in the while loop to:
Sb.append (num&7); Num=num >>> 3;
If you want to write a 16-binary conversion, you can change the two statements in the while loop to:
Sb.append (num&15); Num=num >>> 4;
Java Binary conversion (ignoring positive and negative differences)