错误理解按位操作

时间:2014-05-26 02:56:02

标签: c++ c bit-manipulation bitwise-operators

我有无符号整数(32位),并希望分成3组,每组12位。     但是,我无法正确提取数字。     例如假设我有32位unsigned int,如下所示:

1111 0000 1011 0000 1010 1001 1100 1101  

然后我想要这样的事情:

S1 = 1111 0000 1011 
s2 = 0000 1010 1001 
s3 = 1100 1101 

计划:

    #include<stdio.h>

    int main() {
            short s1,s2,s3 = 0
            unsigned int addr = 4194624;

            s1 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s1);
            s2 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s2);
            s3 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s3);

            return 0;
    }

3 个答案:

答案 0 :(得分:2)

这适合我。

// Just pick up the last 8 bits of addr and
// assign it to s3.
s3 = addr & 0xFF;

// Shift addr by 8 bits to the right, then pick up
// just the last 12 bits of the resulting number, and then
// assign it to s2.
s2 = (addr >> 8) & 0xFFF;

// Shift addr by 20 bits to the right and then assign
// the resulting number to s1.
s1 = (addr >> 20);

答案 1 :(得分:2)

您可以使用这样的功能来提取位:

short f( unsigned int number, int start, int end)
{
    unsigned int mask = (1 << (end - start)) - 1;
    return ( number >> start) & mask;
}

然后:

int main() {

    short s1,s2,s3 = 0;
    unsigned int addr = 4194624;

    s1 = f( addr, 20, 31);
    s2 = f( addr, 8, 19);
    s3 = f( addr, 0, 7);

    printf("%d\n", s1);
    printf("%d\n", s2);
    printf("%d\n", s3);
    return 0;
}

打印:

4

1

64

http://ideone.com/Q5mV94

答案 2 :(得分:1)

从评论中复制 - 看到你有一个32位数字,我所做的是我把它存储在另一个变量然后右移20位所以我的新数字是12位数字,然后在另外两个12位链上完成获得所需数字的相同操作

#includde<stdio.h>
#include<conio.h>

void main()
{
    unsigned long a=4194624,e;
    int b,c,d;
    e=a;
    e=e>>20;
    b=e;
    e=a;
    e=e<<12;
    e=e>>20;
    c=e;
    e=a;
    e=e<<24;
    e=e>>24;
    d=e;
    printf(" %d %d %d ",b,c,d);
    getch(); 
}