C++ Logo

std-proposals

Advanced search

[std-proposals] std::bitset slicing

From: AJ Sutrave <asutrave_at_[hidden]>
Date: Wed, 27 Jul 2022 13:57:31 -0500
Hi,
I was wondering if there was a way to get and set a slice from a bitset. If not, I was wondering if something like this could be added to the std::bitset namespace as helper functions. Strictly speaking, I think we would not really need hi and lo, but I think it makes sense to do some checking on the width/indices. We could also make this a member function of the std::bitset class and then we would not need the bitset_len and bitset parameters.

template<size_t bitset_len, size_t slice_len>
std::bitset<slice_len> get_slice(const std::bitset<bitset_len> bitset, const size_t hi, const size_t lo) {
  assert(slice_len == (hi - lo + 1));
  std::bitset<slice_len> slice;
  for (size_t i = 0; i < slice_len; i++) {
    slice[i] = bitset[i+lo];
  }
  return slice;
}

template<size_t bitset_len, size_t slice_len>
void set_slice(std::bitset<bitset_len> bitset, std::bitset<slice_len> slice, const size_t hi, const size_t lo) {
  assert(slice_len == (hi - lo + 1));
  for (size_t i = 0; i < slice_len; i++) {
    bitset[i+lo] = slice[i];
  }
}


-AJ

Received on 2022-07-27 18:57:35