我想将十进制数转换为二进制数。我想将它们存储在一个数组中。首先,我需要创建一个具有一定长度的数组,以便我可以存储二进制数。之后我执行转换,我是这样做的:
public class Aufg3 {
public static void main(String[] args) {
int[] test = decToBin(12, getBinArray(12));
for(int i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
public static int[] getBinArray(int number){
int res = number, length = 0;
while(res != 0){
res /= 2;
length++;
}
return new int[length];
}
public static int[] decToBin(int number, int[] array){
int res = number, k = array.length-1;
while(res != 0){
if(res%2 == 0){
array[k] = 0;
}else{
array[k] = 1;
}
k--;
res /= 2;
}
return array;
}
}
有什么需要改进的吗?对于 12 的输入,它应该打印 1100。