理解位操作时出错

ERROR in understanding bit-wise operations

本文关键字:出错 位操作      更新时间:2023-10-16

我有unsigned int(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("%dn", s1);
            s2 = addr>>12;
            addr = addr>>12;
            printf("%dn", s2);
            s3 = addr>>12;
            addr = addr>>12;
            printf("%dn", s3);
            return 0;
    }

这对我很有用。

// 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);

您可以使用这样的函数来提取位:

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("%dn", s1);
    printf("%dn", s2);
    printf("%dn", s3);
    return 0;
}

打印:4

1

64年

http://ideone.com/Q5mV94

复制自注释 -看到你有一个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(); 
}