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

How can I cast an std::bitset<N> to an std::bitset<M>?

如果我有一个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);