我怎样才能访问特定比特组从一个变量? [英] How can I access a specific group of bits from a variable?

查看:162
本文介绍了我怎样才能访问特定比特组从一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有位的X号的变量。我怎样才能提取特定比特组,然后在C对他们的工作?

I have a variable with "x" number of bits. How can I extract a specific group of bits and then work on them in C?

推荐答案

您将与一系列的2位逻辑运算的做到这一点。

You would do this with a series of 2 bitwise logical operations.

[[术语的MSB(最高有效位)是最-显著位; LSB(LSB)是最不显著位。假设位从LSB == 0到一些MSB(例如在32位机器上31)。比特位置i重新$ P $的值psents整数的2 ^ I分量的系数。]]

[[Terminology MSB (msb) is the most-significant-bit; LSB (lsb) is the least-significant-bit. Assume bits are numbered from lsb==0 to some msb (e.g. 31 on a 32-bit machine). The value of the bit position i represents the coefficient of the 2^i component of the integer.]]

例如,如果您有 INT X ,并要提取比特×[msb..lsb]包容性的,例如一个4位字段x的一定范围内[7..4]出X [31..0]位,那么:

For example if you have int x, and you want to extract some range of bits x[msb..lsb] inclusive, for example a 4-bit field x[7..4] out of the x[31..0] bits, then:


  1. 通过由LSB位,如移动X右 X>> LSB ,你把x的LSB位在第0除权pression的(至少显著)位,这也正是它需要的。

  1. By shifting x right by lsb bits, e.g. x >> lsb, you put the lsb bit of x in the 0th (least significant) bit of the expression, which is where it needs to be.

现在,你必须屏蔽掉上面的那些MSB指定的任何剩余位。这样的位数是MSB LSB + 1,我们可以形成的1位位掩码字符串长与前pression 〜(〜0℃;<(MSB- LSB + 1))。例如〜(〜0℃;<(7-4 + 1))==〜0b11111111111111111111111111110000 == 0b1111

Now you have to mask off any remaining bits above those designated by msb. The number of such bits is msb-lsb + 1. We can form a bit mask string of '1' bits that long with the expression ~(~0 << (msb-lsb+1)). For example ~(~0 << (7-4+1)) == ~0b11111111111111111111111111110000 == 0b1111.

全部放在一起,你可以提取要与位向量与这个前pression一个新的整数:

Putting it all together, you can extract the bit vector you want with into a new integer with this expression:

(x >> lsb) & ~(~0 << (msb-lsb+1))

例如,

int x = 0x89ABCDEF;
int msb = 7;
int lsb = 4;
int result = (x >> lsb) & ~(~0 << (msb-lsb+1));
//      ==   0x89ABCDE  & 0xF
//      ==   0xE (which is x[7..4])

请有意义吗?

黑客快乐!

这篇关于我怎样才能访问特定比特组从一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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