废话少说,直接上码:
public static void main(String[] args){
int i = 10;//二进制1010
//byte i2 = 0b01010;//jdk7才支持的二级制类型
//System.out.println("0b01010的值是"+i2);
String str = "";
//方法一,求商求余法
System.out.println("方法一:");
while(i!=0){
str =(i%2)+str;//判断i是否可被2整除,可以则末位是0,不然为1
i=i/2; //对i取商运算
}
System.out.print(str);
System.out.println("");
//方法二,移位法+与运算
i = 10;//二进制1010
System.out.println("方法二:");
str = "";
while(i!=0){
str =(i&1)+str;//i&1相当于 1010和0001做与运算,最末一位是啥则是啥
i>>=1; //i右移一位=i/2
}
System.out.print(str);
//方法三,java类
System.out.println("");
i = 10;//二进制1010
System.out.print(Integer.toBinaryString(i));
}
附上java类的方法的实现方法:
/**
* Returns a string representation of the integer argument as an
* unsigned integer in base 2.
*
* <p>The unsigned integer value is the argument plus 2<sup>32</sup>
* if the argument is negative; otherwise it is equal to the
* argument. This value is converted to a string of ASCII digits
* in binary (base 2) with no extra leading {@code 0}s.
*
* <p>The value of the argument can be recovered from the returned
* string {@code s} by calling {@link
* Integer#parseUnsignedInt(String, int)
* Integer.parseUnsignedInt(s, 2)}.
*
* <p>If the unsigned magnitude is zero, it is represented by a
* single zero character {@code '0'} ({@code '\u005Cu0030'});
* otherwise, the first character of the representation of the
* unsigned magnitude will not be the zero character. The
* characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
* '1'} ({@code '\u005Cu0031'}) are used as binary digits.
*
* @param i an integer to be converted to a string.
* @return the string representation of the unsigned integer value
* represented by the argument in binary (base 2).
* @see #parseUnsignedInt(String, int)
* @see #toUnsignedString(int, int)
* @since JDK1.0.2
*/
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
/**
* Convert the integer to an unsigned number.
*/
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedInt(val, shift, buf, 0, chars);
// Use special constructor which takes over "buf".
return new String(buf, true);
}
/**
* Format a long (treated as unsigned) into a character buffer.
* @param val the unsigned int to format
* @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
* @param buf the character buffer to write to
* @param offset the offset in the destination buffer to start at
* @param len the number of characters to write
* @return the lowest character location used
*/
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}