如何在C++中获得整数的j个最高有效位

How can you get the j first most significant bits of an integer in C++?

本文关键字:有效位 整数 C++      更新时间:2023-10-16

我知道要获得整数的前j个最低有效位,可以执行以下操作:

  int res = (myInteger & ((1<<j)-1))

你能为最重要的部分做一些类似的事情吗?

简单右移:(警告,当你想要0位时失败,但你的所有位都失败)

unsigned dropbits = CHAR_BIT*sizeof(int)-j;
//if you want the high bits moved to low bit position, use this:
ullong res = (ullong)myInteger >> dropbits; 
//if you want the high bits in the origonal position, use this:
ullong res = (ullong)myInteger >> dropbits << dropbits;

重要!强制转换必须是类型的未签名版本

同样值得注意的是,当您要求所有(32?)位时,最低j位的代码会失败。因此,可以更容易地进行双重移位:

unsigned dropbits = CHAR_BIT*sizeof(int)-j;
ullong res = (ullong)myInteger << dropbits >> dropbits;

请在此处查看它的工作情况:http://coliru.stacked-crooked.com/a/64eb843b3b255278在这里:http://coliru.stacked-crooked.com/a/29bc40188d852dd3

要获得整数(或者更确切地说是无符号整数,因为有符号整数中的逐位运算会带来痛苦)的j最高位:

unsigned res = myUnsignedInteger & ~(~0u >> j);

CCD_ 3仅由设置比特组成。将j位向右移动会在左侧产生j零位,然后是一位,而反转会在左侧形成j一位,然后再是零,这是我们需要隔离另一个整数的j最高位的掩码。

注意:这是在您希望隔离的位保持在同一位置的假设下进行的,也就是说

(0xdeadbeef & ~(~0u >> 12)) == 0xdea00000