Skip to content

Instantly share code, notes, and snippets.

@tttapa
Created August 15, 2019 18:57
Show Gist options
  • Save tttapa/a286ffe29b549cba2ce048071228db9a to your computer and use it in GitHub Desktop.
Save tttapa/a286ffe29b549cba2ce048071228db9a to your computer and use it in GitHub Desktop.
C++ template function to increase the number of bit in a number uniformly.
#include <climits>
#include <cstdint>
#include <iostream>
template <bool B, class T = void>
struct enable_if {};
template <class T>
struct enable_if<true, T> {
typedef T type;
};
template <bool B, class T = void>
using enable_if_t = typename enable_if<B, T>::type;
template <size_t Bits_out, size_t Bits_in, class T_out, class T_in>
enable_if_t<(Bits_out <= 2 * Bits_in), T_out> increaseBitDepthImpl(T_in in);
template <size_t Bits_out, size_t Bits_in, class T_out, class T_in>
enable_if_t<(Bits_out > 2 * Bits_in), T_out> increaseBitDepthImpl(T_in in) {
constexpr size_t leftShift = Bits_out - Bits_in;
return ((T_out) in << leftShift) |
increaseBitDepthImpl<leftShift, Bits_in, T_out>(in);
}
template <size_t Bits_out, size_t Bits_in, class T_out, class T_in>
enable_if_t<(Bits_out <= 2 * Bits_in), T_out> increaseBitDepthImpl(T_in in) {
constexpr size_t leftShift = Bits_out - Bits_in;
constexpr size_t rightShift = Bits_in - leftShift;
return ((T_out) in << leftShift) | (in >> rightShift);
}
template <size_t Bits_out, size_t Bits_in, class T_out, class T_in>
T_out increaseBitDepth(T_in in) {
static_assert(Bits_in <= sizeof(T_in) * CHAR_BIT,
"Error: Bits_in > bits(T_in)");
static_assert(Bits_out <= sizeof(T_out) * CHAR_BIT,
"Error: Bits_out > bits(T_out)");
return increaseBitDepthImpl<Bits_out, Bits_in, T_out>(in);
}
using std::cout;
using std::endl;
int main() {
for (int i = 0; i < 0x10; ++i) {
cout << increaseBitDepth<4, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<5, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<6, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<7, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<8, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<9, 4, uint16_t, uint8_t>(i) << '\t'
<< increaseBitDepth<16, 4, uint16_t, uint8_t>(i) << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment