Skip to content

Instantly share code, notes, and snippets.

@qrealka
Created June 13, 2018 19:02
Show Gist options
  • Save qrealka/0ec3cf740df5cd124ca6f82c522aa160 to your computer and use it in GitHub Desktop.
Save qrealka/0ec3cf740df5cd124ca6f82c522aa160 to your computer and use it in GitHub Desktop.
pack unpack bits
template <class T, class InputIt, class OutputIt>
void pack_bits_to(InputIt first, InputIt last, OutputIt d_first)
{
static_assert(std::is_integral<T>::value);
while (first != last) {
DataType buf = 0;
for (std::size_t i = 0; i < 8 * sizeof(T); ++i) {
bool bit = (first != last) ? (*(first++)) : 0;
buf = buf | static_cast<DataType>(bit << i);
}
*(d_first++) = buf;
}
}
template <class T, class InputIt, class OutputIt>
void unpack_bits_from(InputIt first, InputIt last, OutputIt d_first)
{
static_assert(std::is_integral<T>::value);
while (first != last) {
for (std::size_t i = 0; i < 8 * sizeof(T); ++i) {
*(d_first++) = (1 & (*first >> i));
}
++first;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment