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

时间:2019-06-09 19:00:29

标签: c++ std-bitset

如果我有一个std::bitset<16>,如何将其转换为std::bitset<32>,高位填充为0?

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

1 个答案:

答案 0 :(得分:3)

如果位数少于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());
}

如果不是,那么您需要将比特集分解为整块,然后将它们放在一起:

#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);