public static void main(String[] args) {
int i =101;
int i2=i;
i =getBinarySystem(i);
System.out.println(i2+"=>转换为二进制:"+i);
i2=i;
i=getDecimalism(i);
System.out.println(i2+"=>二进制转换十进制:"+i);
}
public static Integer getBinarySystem(Integer i){//十进制转二进制
if (i>255){
new RuntimeException("转换失败,二进制最大的数值是255!");
}
String binarySystem ="";
for (int j = 0; j <i; ) {
if (i%2==0){
binarySystem="0"+binarySystem;
}else{
binarySystem="1"+binarySystem;
}
i=i/2;
}
return Integer.parseInt(binarySystem);
}//十进制转二进制
public static Integer getDecimalism(Integer i){
if (i+"".length()>8){
new RuntimeException("请输入正确的二进制数字!");
}
int sum=0;
int count=0;
int s;
int cube;
for (int j = 0; j < i + "".length();) {
s=i%10;
cube=1;
for (int k = 0; k <count; k++) {
cube=cube*2;
}
count++;
sum+=s*cube;
i=i/10;
}
return sum;
}//二进制转换十进制