C语言中从数组中提取最后N位

kokeuurv  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(120)

我有一个C中的无符号字符数组:

unsigned char array[] = { 0xF0, 0xCC, 0xAA, 0xF0}; 
/* Represented as binary: 11110000 11001100 10101010 11110000 */

我想从这个数组中提取最后N位,并将它们存储在一个整数中。例如,如果我想提取最后5位,结果应该是:

int i = 32; /* Represented as binary: 10000 */

我尝试使用BIGNUM库,但我发现它是矫枉过正,有点慢,为这一目的。有没有更有效的方法在C中实现这一点?
随附代码:

unsigned char array[] = { 0xF0, 0xCC, 0xAA, 0xF0}; 
int i = 0; 
int j;
int totalBits = sizeof(array) * 8;  
int startBit = totalBits - 5;  

for (j = startBit; j < totalBits; j++) 
{
            i = i << 1;
            i = i | (array[j] & 1);
}
oxalkeyp

oxalkeyp1#

勇敢的努力!谢谢你展示你的尝试。
我在你的版本中添加了一些评论:

unsigned char array[] = { 0xF0, 0xCC, 0xAA, 0xF0}; 
int i = 0; 
int j;
int totalBits = sizeof(array) * 8;  // currently meaning 32
int startBit = totalBits - 5;  // meaning 27 where '5' is the magic number wanted

for (j = startBit; j < totalBits; j++) 
{
            i = i << 1;
            i = i | (array[j] & 1); // Oops! there is no array[27]! Top element is array[3]!
}

下面是一个粗略的版本,似乎工作:

int main(void) {
    unsigned char arr[] = { 0xF0, 0xCC, 0xAA, 0xF0 }; // Your array (add more! Try it out!)

    union { // providing for up to N = 64bits (on my system)
        unsigned char c[8];
        unsigned long l;
    } foo;

    foo.l = 0; // initialise

    size_t sz = sizeof arr / sizeof arr[0]; // source byte count
    size_t n = 0; // destination byte count

    // wastefully copy as many bytes as are available until 'foo' is a full as possible
    // Notice the 'endian-ness' of index n going from 0 to 8.
    // Other hardware could change this to count downward, instead.
    for( size_t i = sz; i && n < sizeof foo; ) {
        foo.c[ n++ ] = arr[ --i ]; // grab one byte
        printf( "%x\n", foo.l ); // debugging
    }

    int N = 5;
    foo.l &= (1<<N)-1; // Mask off the low order N bits from that long

    printf( "%x\n", foo.l );

    return 0;
}

希望这对你有帮助。
最后警告:在这个代码中,N63...应该增加检查N不超过累加器foo的宽度,如果N正好是那个数字,则绕过移位和掩码操作。
PS:当使用位操作时,使用unsigned数据库通常更安全。一些C实现显然反对不适当地篡改符号位。

相关问题