Skip to content

Instantly share code, notes, and snippets.

@engelmarkus
Created April 20, 2016 23:21
Show Gist options
  • Save engelmarkus/c47d528af0fb99900b22e37708602fab to your computer and use it in GitHub Desktop.
Save engelmarkus/c47d528af0fb99900b22e37708602fab to your computer and use it in GitHub Desktop.
Convert a compile-time constant to a char-array containing the binary representation.
#include <iostream>
template <unsigned long long N, char... C>
constexpr auto to_bin = to_bin<(N >> 1), '0' + (N & 1), C...>;
template <char... C>
constexpr char to_bin<0, C...>[] = { C..., '\0' };
template <unsigned long long N, size_t L, char... C>
constexpr auto to_bin_fixed = to_bin_fixed<(N >> 1), L - 1, '0' + (N & 1), C...>;
template <unsigned long long N, char... C>
constexpr char to_bin_fixed<N, 0, C...>[] = { C..., '\0' };
int main() {
std::cout << to_bin<42> << "\n";
// => "101010"
std::cout << to_bin_fixed<42, 8> << "\n";
// => "00101010"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment