使用位操作提取位 [英] Extracting bits using bit manipulation

查看:112
本文介绍了使用位操作提取位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个32位无符号整数,我需要在给定位置提取位,并从这些位中提取一个新的数字.例如,如果我有一个0xFFFFFFFF并且想要位0,10,11,我的结果将是7(111b).

I have a 32-bit unsigned int and I need to extract bits at given positions and make a new number out of those bits. For example, if I have a 0xFFFFFFFF and want bits 0,10,11 my result will be 7 (111b).

这是我的尝试,它会正确提取位,但不会产生正确的结果.我将结果左移1位,并与提取的位进行与"运算,显然这是不正确的吗?

This is my attempt, it extracts the bits correctly but doesn't create the correct result. I'm shifting the result 1 place left and ANDing it with my extracted bit, apparenlty this is incorrect though?

我还可以确定有一种更优雅的方法吗?

I'm also sure there is probably a much more elegant way to do this?

#define TEST 0xFFFFFFFF

unsigned int extractBits(unsigned short positions[], unsigned short count, unsigned int bytes)
{
    unsigned int result = 0;
    unsigned int bitmask = 0;
    unsigned short bit = 0;
    int i = 0;

    for(i = 0; i < count; i++) {
        bitmask = 2 << (positions[i] -1);
        if(bitmask == 0) bitmask = 1;

        bit = bytes & bitmask;
        bit = bit >> positions[i];

        result = result << 1;
        result = result & bit;  
    }

    if(result != 31) {
        printf("FAIL");
    }

    return result;
}

int main(void)
{
    unsigned short positions[5] = {8, 6, 4, 2, 0};
    unsigned int result = extractBits(positions, 5, TEST);

    printf("Result: %d\n", result);

    return 0;
}

推荐答案

由于您要选择单个位,因此没有理由将位掩码设置为变量.只需将所需的位转换为单位位,并使用1的掩码即可.例如:

Since you are picking off individual bits, there's no reason to make the bit mask a variable; just shift the desired bit into the units bit, and use a mask of 1. E.g.:

...
result = (2*result) | ((bytes >> positions[i]) & 1);
...

许多编译器会为2*resultresult<<1生成相同的代码,因此请随意使用.

Many compilers generate the same code for 2*result and result<<1, so use whichever you like.

请注意,如果您正在设计接口,并且没有充分理由对positions[]count使用short整数,那么就不要这样做.保持一致,并以相同的方式指定所有整数.

Note, if you are designing the interface and don't have good reasons for using short integers for positions[] and count as you do, then don't. Be consistent and specify all the integers the same way.

这篇关于使用位操作提取位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆