什么是最快的方法(在常见的现代架构上的cpu周期方面),len从位置开始生成位设置为1 的掩码pos:
template <class UIntType>
constexpr T make_mask(std::size_t pos, std::size_t len)
{
// Body of the function
}
// Call of the function
auto mask = make_mask<uint32_t>(4, 10);
// mask = 00000000 00000000 00111111 11110000
// (in binary with MSB on the left and LSB on the right)
Run Code Online (Sandbox Code Playgroud)
另外,是否有任何编译器内在函数或BMI函数可以帮助?
一般来说,bit shift(>> , <<)允许我们分频/乘以^2
示例:
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Run Code Online (Sandbox Code Playgroud)
= 2(基数10)
对于负数:
同样,-9 >> 2收益率-3,因为符号被保留:
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
Run Code Online (Sandbox Code Playgroud)
但是看看>>>哪些行为对于正数而言是相同的,但是对于负数,行为却不同:
零位从左侧移入
我0从左边找不到任何理由/用法从左边移动 (这使得整个数字为正):
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >>> 2 (base 10): …Run Code Online (Sandbox Code Playgroud) 我正在尝试执行以下操作:
写一个func
setbits(x,p.n,y),返回x的n位从p设置到最右边n位的位置开始,y其他位保持不变?
我试过这样但没有得到正确的答案.任何人都可以告诉我哪里错了吗?
unsigned setbits(unsigned x,int p,int n,unsigned y)
{
return (x>>p & (y|(~0<<n)));
}
Run Code Online (Sandbox Code Playgroud)