C ++:掩码和解码位 [英] C++: Mask and decoding bits

查看:101
本文介绍了C ++:掩码和解码位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚遇到一个我不了解的功能,我想知道您能否向我解释它.

I just came across a function I dont understand, and I was wondering if you could explain it to me.

unsigned long long x(unsigned long long value, int begin, int end)
{
    unsigned long long mask = (1 << (end - begin)) - 1;
    return (value >> begin) & mask;
}

谢谢
uksz

Thanks
uksz

推荐答案

上面的函数用作从数字中提取一定范围的位的掩码.它可以分为四个步骤.

The above function serves as a mask to extract a range of bits from a number. It can be broken down into four steps.

第一步:

mask = 1UL << (end - begin)

<<在逻辑上将1左移end - begin位.由于1的二进制为000001,所以移位3将对应于001000.

The << logically shifts 1 to the left by end - begin bits. Since the binary of 1 is 000001, a shift by 3 would correspond to 001000.

第二步:

mask = mask - 1

从上一步中我们已经确定,此时的掩码将是一个零序列,然后是一个零,然后是end - begin个零数目.从该数字中减去1将导致end - begin最低有效位为1,其他所有内容均为0.从前面的示例中减去1会得出000111.

We have established from the previous step that mask at that point would be a sequence of zeroes, followed a one, followed by end - begin number of zeroes. Subtracting 1 from such a number will result in the end - begin least significant bits being 1, with everything else as 0. Subtracting 1 from our previous example yields 000111.

第三步:

value >> begin

这将逻辑上将目标编号(我们需要从中提取比特的那个数字)向右移begin比特.由于我们希望位在begin to end范围内,因此我们可以删除begin之前的位.

This will logically shift the target number (the one from which we need to extract bits) to the right by begin bits. Since we want the bits in the range begin to end, we can leave remove the bits before begin.

第四步:

(value >> begin) & mask

按字符与掩码进行运算将导致提取移位数的前begin - end位.这是因为0 & x = 01 & x = x.

Taking the characterwise AND with the mask will result in the first begin - end bits of the shifted number being extracted. This is because the 0 & x = 0 and 1 & x = x.

正如Bathsheba在另一个答案中指出的那样,应注意写1UL,以确保要移位的数字为unsigned int.否则,将int移更多的位是不确定的行为. 1UL是值为1unsigned long long int.

As pointed out in the other answer by Bathsheba, care should be taken to write 1UL to ensure that the number being shifted is an unsigned int. Else shifting an int by more bits in that int is undefined behavior. 1UL is an unsigned long long int with the value 1.

这篇关于C ++:掩码和解码位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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