分别查看内存中的每个位

时间:2014-11-06 02:54:44

标签: c bit-manipulation

在阅读问题how to get bit by bit data from a integer value in c?之后,我看到如果我想查看整数中的每个位,我应该右移整数并屏蔽它。但我想知道是否可以在没有如此复杂的代码的情况下访问内存中的每个位?使用pointer或类似的东西。

3 个答案:

答案 0 :(得分:1)

在C中,位移操作,如移位是在位级操作变量的唯一方法之一。它的表达方式可能有点“丑陋”。乍一看,但通过练习喜欢一切,很快就会很容易理解。

坚持下去。

这是一篇很有兴趣的文章: A bit of fun: fun with bits

答案 1 :(得分:1)

可以在没有移动和遮蔽的情况下进行,但它不会少于复杂和#34;这样做:

#include <stdio.h>
#include <stdbool.h>

unsigned int ui_pow(unsigned int base, unsigned int exponent)
{
    unsigned int result = 1;
    for ( unsigned int i = 1; i <= exponent; ++i ) {
        result *= base;
    }
    return result;
}

bool bit_is_set_one(unsigned int n, unsigned int bit)
{
    return (n >> bit) & 1;
}

bool bit_is_set_two(unsigned int n, unsigned int bit)
{
    return (n / ui_pow(2, bit)) % 2;
}

int main(void)
{
    bool all_equal = true;

    for ( unsigned int i = 0; i < 65535; ++i ) {
        for ( unsigned int j = 0; j < 16; ++j ) {
            if ( bit_is_set_one(i, j) != bit_is_set_two(i, j) ) {
                all_equal = false;
            }
        }
    }

    printf("Methods%s give equal results.\n", all_equal ? "" : " do not");

    return 0;
}

输出:

paul@thoth:~/src/sandbox$ ./altshift
Methods give equal results.
paul@thoth:~/src/sandbox$ 

答案 2 :(得分:-1)

如果您知道位位置,则可以在不进行移位的情况下进行掩码。 例如:(i&amp; 0x02) 如果右边的第2位是1,你将得到0x02,如果第2位是0,你将得到0x00。 通常使用宏:#define BitMask(i)(1&lt;&lt;(i)) 对于常数i,转换将在编译阶段处理,并且不会出现在最终的二进制文件中。