位移和奇怪的输出

时间:2013-12-03 04:12:12

标签: c bit-manipulation

所以如果有人能解释什么事情发生以及我需要在这里解决的问题,那么我会对结果感到难过。所以我的目标是每次移动(i)1位,直到p& i = j在二进制文件中看起来应该是这样的

 101011100 & 1 != 100 
 101011100 & 10 != 100
 101011100 & 100 != 100 //true

但是我让我跳过p并且旋转pos并且否定所有其他数字 这是我的代码:

int i=1;
int p= // some memmory addres for this case lets just say p = 101011100
int j=1;
while(p&i != 1<j){

i=i+(i<1);
printf("i:%d\n",i);
}

2 个答案:

答案 0 :(得分:0)

要检查条件p&i!=j,我建议的代码是:

int i=1;
int p = //binary
int j = 4;
while((p&i)!=j)
{
    i = i<<1;
    printf("i: %d\n",i);
    //Alter j value if needed
}           

根据提供的示例,j值为100.因此,在这种情况下,我更喜欢j为4,因为100的十进制等值为4。

答案 1 :(得分:0)

您可以使用十六进制或二进制编码,如下所示:

#include <stdio.h>

static void print_binary(unsigned short x)
{
    for (int b = 32768; b != 0; b /= 2)
    {
        printf("%d", (b & x) != 0);
        x &= ~b;
    }
}

static unsigned short scan_binary(char const *binary)
{
    unsigned short u = 0;
    char c;
    while ((c = *binary++) != '\0')
    {
        /* GIGO: if it isn't a '0' or a '1', you get what you deserve! */
        u = (u << 1) | (c - '0');
    }
    return u;
}

int main(void)
{
    /* Working in hex - simpler */
    int p = 0x15C;
    for (int i = 0; i < 16; i++)
    {
        if ((p & (1 << i)) == 0x04)
            printf("Shift %d yields 0x%.4X from 0x%.4X and 0x%.4X\n",
                   i, (p & (1 << i)), p, (1 << i));
    }

    /* Working in binary - harder */
    char b1[] = "101011100";
    char b2[] = "100";
    unsigned u1 = scan_binary(b1);
    unsigned u2 = scan_binary(b2);
    for (int i = 0; i < 16; i++)
    {
        if ((u1 & (1 << i)) == u2)
        {
            printf("Shift %d yields ", i);
            print_binary(p & (1 << i));
            printf(" from ");
            print_binary(u1);
            printf(" and ");
            print_binary(1 << i);
            putchar('\n');
        }
    }

    return 0;
}

输出:

Shift 2 yields 0x0004 from 0x015C and 0x0004
Shift 2 yields 0000000000000100 from 0000000101011100 and 0000000000000100

不使用二进制文件的一个原因是它会产生很长的数字字符串。

相关问题