【问题标题】:How to Assign a bitset to an unsigned char vector?如何将位集分配给无符号字符向量?
【发布时间】:2017-09-24 04:30:25
【问题描述】:

我正在使用具有一些十六进制值的无符号字符向量。

   std::vector<unsigned char> sync;
   sync.push_back(0x50);
   sync.push_back(0x51);
   sync.push_back(0x52);
   sync.push_back(0x53);

然后,使用位集,我将同步 [3]“变形”为 8 位表示。这是因为我需要破坏/切换其中的任何随机位。

    srand(time(NULL));
    int bitsetIndex= random()%8; 
    std::bitset<8> manipulator(v[3]); //v is the vector argument which takes "sync" vector
                                      //by reference 
    manipulator.flip(bitsetIndex);

由于我通过引用传递我的向量,因此我想对其进行更改。 IE。 无论我对我的 bitset 做了什么更改,我也想将它提交给向量。但是,我不确定如何将位集转换为无符号字符以及如何将其分配给我的向量,以更新我的向量 sync

【问题讨论】:

  • v[3] ^= (1 &lt;&lt; bitsetIndex);。你不需要bitset
  • @IgorTandetnik 谢谢,但我想知道如何使用 bitset 来做到这一点。我只是想更好地理解 bitset 并学习如何使用它。
  • 如果您不确定std::bitset,请查看此参考:en.cppreference.com/w/cpp/utility/bitset

标签: c++ vector std-bitset


【解决方案1】:

致电manipulator.to_ulong()。 (缩小转换为您的unsigned char 将是无害的。)

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2013-02-23
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多