我正在编写一个函数,按照以下说明将 int 数字转换为他们的 int numberbinary: 假设我们希望将十进制 57 转换为二进制。我们首先写位置 从右到左列的值,直到我们到达位置值更大的列 比十进制数。我们不需要该列,因此我们将其丢弃。于是,我们先 写:
位置值:64 32 16 8 4 2 1
然后我们丢弃位置值为 64 的列,留下:
位置值:32 16 8 4 2 1
接下来,我们从最左边的列向右处理。我们把 32 分成 57,然后 观察到 57 中有一个 32,余数为 25,因此我们在 32 列中写 1。 我们将 16 除以 25 并观察到 25 中有一个 16 余数为 9 并写成 1 在第 16 列中。我们将 8 分成 9,然后观察到 9 中有一个 8 具有 1 的余数。接下来的两列在它们的位置时分别产生 0 的商 值分为1,所以我们在第4列和第2列写0。最后,1 乘以 1 就是 1,所以 我们在第 1 列写 1。这产生:
位置值:32 16 8 4 2 1 符号值:1 1 1 0 0 1
我写了这个函数,试图跟随解释的脚步。当dec = 10 且c2 = 4 时,不应继续while 循环,因为10 <= 4 为假,但条件为真。有人可以解释这里发生了什么吗?
public static int decimaltobinary(int dec){}{
int bin = 0,it;
int c1,c2;
while(dec>0){
it = 1;
do{
c2 = (int)Math.pow(2, it +1);
c1 = (int)Math.pow(2, it);
}while(dec <= c2 && dec < c1);
bin += Math.pow(10, it - 1);
dec = dec % c1;
}
return bin;
}
最佳答案
如果你不需要自己的算法,你可以做得更容易:
public int toBinary(int decimal) {
String binaryString = Integer.toBinaryString(decimal);
return Integer.parseInt(binaryString);
}
如果你想制作自己的算法,位攻击会更容易。对于整数的二进制表示,int 似乎是一个糟糕的容器,因为您只能容纳 9 位。
public int toBinaryBitBashing(int decimal) {
int bitCount = 6;
int bit = 0;
int binary = 0;
int power = 1;
for(int i=0; i<bitCount; ++i) {
bit = (decimal >> i) & 1;
binary += bit * power;
power *= 10;
}
return binary;
}
关于java - Java中的十进制转二进制函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26108796/