c - 了解此函数中的位运算

标签 c binary bit-manipulation

为简单起见,我们假设传递给此函数的整数是 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/

相关文章:

c++ - 将十进制数转换为二进制数的意外结果

.net - 下载二进制文件的更好方法

binary - 如何在python中对字符串进行二进制编码?

c++ - 使用指针时的注意事项

比较两个输入的数字是否相同

c - 如何正确使用C中的read函数?

c++ - 等同于 PEXT Haswell 指令的标准 C++11 代码(并且可能会被编译器优化)

java - C 与 Java 中的随机数生成

bit-manipulation - 有哪些利用按位运算符的好方法?

java - 16位偏移和24位偏移是什么意思?我如何使用java进行这样的计算