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;
}//二進制轉換十進制