c++ - 如何将 std::bitset<N> 转换为 std::bitset<M>?

标签 c++ std-bitset

如果我有一个 std::bitset<16> , 我怎样才能把它转换成 std::bitset<32>高位补0?

std::bitset<16> a = 0xFF00;
std::bitset<32> b = a;  // error

最佳答案

如果位数小于 ullong_limits::digits(通常为 64),则可以通过中间 unsigned long long 进行转换:

#include <limits>
#include <bitset>

template<size_t M, size_t N>
std::bitset<M> resize(std::bitset<N> const& in) {
    using ullong_limits = std::numeric_limits<unsigned long long>;
    static_assert(M <= ullong_limits::digits);
    static_assert(N <= ullong_limits::digits);
    return std::bitset<M>(in.to_ullong());
}

如果不是,则需要将 bitset 分解为 ullong 片段,然后将它们放回一起:

#include <limits>
#include <bitset>
#include <utility>

namespace detail {
    using ullong_limits = std::numeric_limits<unsigned long long>;

    template<size_t N>
    constexpr std::bitset<N> all_ullong_bits() {
        return std::bitset<N>(ullong_limits::max());
    }

    /** Resize a bitset, but keeping only the nth ullong */
    template<size_t N, size_t I, size_t M>
    std::bitset<N> resize_nth_ullong(std::bitset<M> const& in) {
        return std::bitset<N>(
            (
                (in >> (ullong_limits::digits * I)) & all_ullong_bits<M>()
            ).to_ullong()
        ) << (ullong_limits::digits * I);
    }

    template<size_t M, size_t N, size_t... I>
    std::bitset<M> resize_helper(std::bitset<N> const& in, std::index_sequence<I...>) {
        return (resize_nth_ullong<M, I>(in) | ... | std::bitset<M>());
    }
}

template<size_t M, size_t N>
std::bitset<M> resize(std::bitset<N> const& in) {
    return detail::resize_helper<M>(in, std::make_index_sequence<
        (N + detail::ullong_limits::digits - 1) / detail::ullong_limits::digits
    >{});
}

无论哪种情况,您都可以使用

std::bitset<32> b = resize<32>(a);

关于c++ - 如何将 std::bitset<N> 转换为 std::bitset<M>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517542/

相关文章:

c++ - 如何迭代所有 malloc block (glibc)

c++ - 根据 std::bitset<N> 增加 std::vector<T> 内的元素

C++ 位集引用

c++ - 使用 std::bitset 或相同大小的基本类型?

c++ - 从 std::bitset::operator[] 推导模板

c++ - OpenCV:如何在文件中存储描述符?

c++ - 不会为 C++ 创建类模板

c++ - 不确定的进度条?

c++ - QSqlQuery 没有正确回答