[英]Setting bits on cpp_int
Silly question but, does setting bits on a cpp_int
from the boost
library work the same as normal numbers?愚蠢的问题,但是,在boost
库中的cpp_int
上设置位是否与正常数字相同?
For instrance, I tried to set some bits on a number like so:例如,我尝试在一个数字上设置一些位,如下所示:
vector<bool> bits; //contains 000000000000011010001100101110110011011001101111
cpp_int M = 0;
int k = 48;
for(bool b : bits) M ^= (-b ^ M) & (1UL << k--);
bits.clear();
bits = toBinary(M); //contains 11001011101100110110011011111
The toBinary(cpp_int&x)
method I have gets bits from the number in the simplest way:我使用的toBinary(cpp_int&x)
方法以最简单的方式从数字中获取位:
vector<int> toBinary(cpp_int&x) {
vector<int> bin;
while (x > 0) {
bin.push_back(int(x % 2));
x /= 2;
}
reverse(bin.begin(), bin.end());
return bin;
}
I can understand losing the 14 zeros in the beginning, what I don't understand is why do lose not 14 but 20 whole bits.我可以理解一开始丢失 14 个零,我不明白的是为什么不丢失 14 位而是 20 个整位。 I am fairly new to the boost
library, so it's most likely a rookie mistake.我对boost
库boost
陌生,所以这很可能是一个新手错误。
Probably unsigned long
is 32 bit on your system.可能unsigned long
在您的系统上是 32 位。 Thus the first masks generated with (1UL << k--)
with k--
being 48 to 32 are not what you expect (it's undefined behaviour).因此,使用(1UL << k--)
生成的第一个掩码,其中k--
为 48 到 32 不是您所期望的(这是未定义的行为)。
You can fix this by using a larger type, like unsigned long long
, like M ^= (-b ^ M) & (1ULL << k--);
您可以使用更大的类型来解决此问题,例如unsigned long long
,例如M ^= (-b ^ M) & (1ULL << k--);
. .
If you have more than 64 bits, you can probably use cpp_int
for more bits, like M ^= (-b ^ M) & (cpp_int(1ULL) << k--);
如果您有超过 64 位,您可能可以使用cpp_int
获得更多位,例如M ^= (-b ^ M) & (cpp_int(1ULL) << k--);
, or a more economical solution like: ,或更经济的解决方案,例如:
cpp_int mask = 1;
mask <<= bits.size();
for (bool b : bits) {
M ^= (-b ^ M) & mask;
// Though that can really be `if (b) M |= mask;`
mask >>= 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.