如何在C++中获得整数的j个最高有效位
How can you get the j first most significant bits of an integer in C++?
我知道要获得整数的前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
相关文章:
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 如何在整数中找到最低有效位(LSB)的位置?c ++
- 从两个 4x64 位整数数组中获取取模
- 在 c++ 中输出 64 位整数
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 在 64 位整数内旋转(90°)位矩阵(最多 8x8 位)
- 如何通过COM接口将64位整数从C++发送到C#
- GMP-将64位整数存储在mpz_t/mpz_class中,并返回64位整数
- 将74位整数转换为以31为底的整数
- 如何创建128位整数文本
- 如何忽略32位整数中的特定位
- int64_t 不包含 13 位整数
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- MongoDB C++ 驱动程序 - 8 位和 16 位整数?
- 有效地将 16 位整数哈希为 256 位空间
- 如何在C++中获得整数的j个最高有效位
- 一种在C++中执行基本 128 位整数计算的有效方法
- 以 64 位整数或相邻位的有效方法
- 在C语言中,64位整数(uint64_t)在Unix和Windows上都有效
- 如何有效地将8个17位整数转换为17个8位整数