为简单起见,我们假设传递给此函数的整数是 9
,即二进制形式的 1001
。
在 C
中将我自己的整数写入二进制函数一直是我一段时间以来的目标。我用来简写数字的二进制值的方法如下(如上所述使用 9
):
9 / 2 = 4.5 (remainder) = 1
4 / 2 = 2 (no remainder) = 0
2 / 2 = 1 (no remainder) = 0
1 / 1 = 1 (remainder) = 1
因此,如果您反转 1 0 0 1
,我们将得到 9
的二进制值,它仍然是 1 0 0 1
.
但是在浏览了这个站点之后,我发现整数的二进制值可以通过一些“简单”的按位算法找到。我在本站的另一篇文章中找到了一个功能,并将其改编成我自己的功能:
char *itob(int integer)
{
char *bin = 0X00, *tmp;
int bff = 0;
while(integer)
{
if(!(tmp = realloc(bin, bff + 1)))
{
free(bin);
printf("\nError! Memory allocation failed while building binary string.");
return 0x00;
}
bin = tmp;
if(integer & 1) bin[bff++] = '1';
else bin[bff++] = '0';
integer >>= 1;
}
bin[bff+1] = 0x00;
return bin;
}
这是我如何理解正在发生的事情以及我的问题(显示为评论)
1001 & 1 = 1 so put a 1 into the buffer //what is & doing that makes it equate to 1? Is it because the first digit in that sequence is a 1?
shift the bits in 1001 to the right one time
0010 & 1 != 1 so move a 0 into the buffer //same question as before is & just looking at the 0 because it is the first digit in the sequence?
shift the bits in 0010 to the right one time
0100 & 1 != 1 so move a 0 into the buffer //same question as before
shift the bits in 0100 to the right one time
1000 & 1 = 1 so put a 1 into the buffer //same question as before (at this point I'm thinking my theory is correct but I'm still not entirely sure)
shift the bits in 1000 to the right one time
loop ends
所以正如我在评论中提到的,这就是我认为在我的程序中正在发生的事情,但我不是 100% 确定。另外我不确定这是否是将十进制转换为二进制的最佳方法。 (我已经知道,如果 integer
出于某种原因成为 0
,我最终会在尝试时尝试取消引用 NULL 指针
释放由 itob()
分配的内存以及其他一些小问题)但是除了我之前已经问过的问题之外,还有更好的方法或更合适的方法来进行这种转换吗?
最佳答案
不是,测试和轮类的顺序是
1001 & 1 => 1 then shift right
100 & 1 => 0 "
10 & 1 => 0 "
1 & 1 => 1 "
生成的整数 0 使循环终止。所以它所做的是从最低有效位开始测试每个位,然后在缓冲区中附加 0 或 1。我会说这是倒退的,因为当作为字符串打印时,位序列与最常用的位序列相反,其中最低有效位是最右边的位。
关于c - 了解此函数中的位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306386/