public class wx
{
public static void main(String arg[])
{
int x,y,z;
x=110;
y=6;
z=x&y;
System.out.println("\tx="+Integer.toBinaryString(x));
System.out.println("\tx&y="+Integer.toBinaryString(x&y));
}
}
首先你要明白10进制转2进制的原理
将要转换的数与2取模,在取商,用商在和2取模,直到商为0或1,最后将因此得到的模逆序合并
例如110转2进制的算法
110%2=0,110/2=55;55%2=1,55/2=27,27%2=1,27/2=13,13%2=1,13/2=6,6%2=0,6/2=3,3%2=1,3/2=1,
转换为2进制即为1101110
public class Untitled1 {
public static void main(String arg[]) {
int x, y, z;
x = 110;
String sum;
String str = "";
for (int i = 0; ; i++) {
sum = String.valueOf(x % 2);
str = str + sum;
x = x / 2;
if (x == 0 || x == 1) {
str = str + String.valueOf(x);//把最后一个得到的商加进去
break;
}
}
StringBuffer strb = new StringBuffer(str);
strb.reverse();//将字符串倒序
System.out.println(strb.toString());
}
}