gpt4 book ai didi

c++ - 从包含十六进制数的 std::string 或 QString 创建 std::bitset 或 QBitArray

转载 作者:行者123 更新时间:2023-11-28 05:40:58 24 4
gpt4 key购买 nike

有没有什么方法可以从十六进制 std::stringQString 构造一个 std::bitset ,反之亦然而不执行二进制轮类操作?我知道如何这样做,但我想知道是否可以使用 C++ 流或类似的东西来做到这一点。

到目前为止,这是我的代码(试图避免受到版主的抨击):

QString data("aabbccddeeff");
QByteArray temp = QByteArray::fromHex(data.simplified().toLatin1());
QBitArray bits(temp.count()*8);
for(int i=0; i<temp.count(); ++i) {
for(int b=0; b<8;b++) {
bits.setBit( i*8+b, temp.at(i)&(1<<(7-b)) );
}
}

最佳答案

您可以将十六进制字符串转换为整数,并从中构造一个位集。

#include <iostream>
#include <sstream>
#include <bitset>
#include <string>

using namespace std;

int main()
{
string s = "0xA";
stringstream ss;
ss << hex << s;
unsigned n;
ss >> n;
bitset<32> b(n);
// outputs "00000000000000000000000000001010"
cout << b.to_string() << endl;
}

关于c++ - 从包含十六进制数的 std::string 或 QString 创建 std::bitset 或 QBitArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com