从Integer C ++获取n LSB

时间:2017-02-12 18:49:14

标签: c++ bit-shift significant-digits

所以我将一个unsigned int传递给了我的函数。现在我必须获取该整数的n个LSB位,并使用它来访问大小为2^n的数组中的位置。

例如,如果我的数组大小为1024,则n = 10。

我目前正在这样做:

unsigned int location = my_unsigned_int << n;

然而,这并不起作用,因为location最终会变得太大而且超出范围。

1 个答案:

答案 0 :(得分:2)

您可以屏蔽您想要的位:

unsigned int location = my_unsigned_int & ((1<<n) - 1);

这假设您的int大小至少为n+1位。