Created
June 13, 2018 19:02
-
-
Save qrealka/0ec3cf740df5cd124ca6f82c522aa160 to your computer and use it in GitHub Desktop.
pack unpack bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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