Skip to content

Instantly share code, notes, and snippets.

@sjolsen
Last active December 23, 2015 00:49
Show Gist options
  • Save sjolsen/6556149 to your computer and use it in GitHub Desktop.
Save sjolsen/6556149 to your computer and use it in GitHub Desktop.
Binary Literals (C++11)
#include <climits>
template <char c>
inline constexpr
unsigned long long int binary_digit ()
{
static_assert (c == '0' || c == '1', "bad bit in binary literal");
return (c - '0');
}
template <char...>
struct binary_literal;
template <char first, char... rest>
struct binary_literal <first, rest...>
{
static inline constexpr
unsigned long long int value ()
{
return (binary_digit <first> () << sizeof... (rest)) + binary_literal <rest...>::value ();
}
};
template <>
struct binary_literal <>
{
static inline constexpr
unsigned long long int value ()
{
return 0;
}
};
template <char... str>
inline constexpr
unsigned long long int operator "" _b ()
{
static_assert (sizeof... (str) <= sizeof (unsigned long long int) * CHAR_BIT,
"binary literal too long");
return binary_literal <str...>::value ();
}
#include <iostream>
int main ()
{
std::cout << 1010_b << std::endl;
// Will fail to compile:
// std::cout << 2020_b << std::endl;
// Will also fail to compile:
// std::cout << 10101010101010101010101010101010101010101010101010101010101010101_b << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment