繁体   English   中英

在 cpp_int 上设置位

[英]Setting bits on cpp_int

愚蠢的问题,但是,在boost库中的cpp_int上设置位是否与正常数字相同?

例如,我尝试在一个数字上设置一些位,如下所示:

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

我使用的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;
  }

我可以理解一开始丢失 14 个零,我不明白的是为什么不丢失 14 位而是 20 个整位。 我对boostboost陌生,所以这很可能是一个新手错误。

可能unsigned long在您的系统上是 32 位。 因此,使用(1UL << k--)生成的第一个掩码,其中k--为 48 到 32 不是您所期望的(这是未定义的行为)。

您可以使用更大的类型来解决此问题,例如unsigned long long ,例如M ^= (-b ^ M) & (1ULL << k--); .

如果您有超过 64 位,您可能可以使用cpp_int获得更多位,例如M ^= (-b ^ M) & (cpp_int(1ULL) << k--); ,或更经济的解决方案,例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM