我需要以二进制形式转换一些十进制数,并在C ++中将由1和0组成的字符串存储为矩阵中的行。 关于转换,我找到了这个简单的解决方案:
std::string binary = std::bitset<8>(128).to_string();
现在,我可以简单地扫描字符串并将每个字符转换为1或0,填充矩阵的行。 有没有办法,C ++函数(或函数组合)允许我避免扫描每个位字符串的成本?
感谢您的帮助。
答案 0 :(得分:1)
首先无法转换为std::string
,然后将其转换为1
/ 0
,您只需使用{{std::bitset
访问[]
内的位即可1}}:
#include <vector>
#include <bitset>
#include <iostream>
using BitRow = std::bitset<8>;
using BitMatrix = std::vector<BitRow>;
void print(const BitMatrix& bm)
{
for(const BitRow& row : bm)
{
for (std::size_t i=0; i < row.size(); ++i)
{
std::cout << row[i] << " ";
}
std::cout << std::endl;
}
}
int main()
{
BitMatrix bitMatrix;
bitMatrix.push_back(128);
bitMatrix.push_back(64);
print(bitMatrix);
}