首页 > 解决方案 > 有什么方法可以直接将整数的按位表示形式转换为 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++ 中有没有直接的方法来实现这一点?(我不是在寻找逐次划分的方法)

标签: 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;
}

推荐阅读