c++ - 有什么方法可以直接将整数的按位表示形式转换为 C++ 中的向量?
问题描述
我想将无符号整数的按位表示直接转换为 c++ 中的 vector<int> 或 vector<bool>
例如:
unsigned un = 203;//bitwise representation: (multiple 0) 1100 1011
//……
//I want a vector like this:
vector<int> unv = {1,1,0,0,1,0,1,1};
//or
vector<bool> unv2 = {1,1,0,0,1,0,1,1};
c++ 中有没有直接的方法来实现这一点?(我不是在寻找逐次划分的方法)
解决方案
您可以使用std::generate
标准库中的函数。可在此处找到该功能的说明。
这一点,我们将使用一个有状态的 Lambda 并一点一点地屏蔽掉。结果将存储在std::vector
所以,这是一个典型的单线。我不确定,这对你来说是否“直接”足够了。但正如所说。只有一种说法。. .
请查看许多可能的解决方案之一:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <cmath>
int main() {
unsigned int un = 203u;
// Create a std::vector, with the needed size
std::vector<int> unv(std::ceil(std::log2(un)));
std::vector<bool> unv2(std::ceil(std::log2(un)));
// Generate the content for the vector
std::generate(unv.rbegin(), unv.rend(), [&un, mask = 1u]() mutable{ int result = un & mask ? 1 : 0; mask <<= 1; return result; });
std::generate(unv2.rbegin(), unv2.rend(), [&un, mask = 1u]() mutable { bool result = un & mask; mask <<= 1; return result; });
// Show result
for (const int i : unv) std::cout << i; std::cout << '\n';
for (const bool i : unv) std::cout << std::boolalpha << i << ' '; std::cout << '\n';
return 0;
}
推荐阅读
- javascript - React 组件未在地图循环内加载
- python - 将一列拆分并编码为 n 列,包含 0 和 1
- html - 顶部的背景颜色和 svg 渐变将 svg 带到 fornt
- python - 计算曲线内的面积
- java - 角度从 POST 响应中获取字符串
- python - Python:使用参考列表的一种热编码
- git - 防止 Git Push live master 更改文件权限和所有权
- azure - 是否可以在 Azure Pipelines 模板 yaml 中混合地图参数?如何?
- java - Java ObjectInputStream 给出 java.io.EOFException
- python - 将 JSON 转换为目录中所有 .json 文件的 XLSX