Skip to content

Instantly share code, notes, and snippets.

@kjk
Last active July 21, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjk/fe86de3b2a3f5071478225350e1126ac to your computer and use it in GitHub Desktop.
Save kjk/fe86de3b2a3f5071478225350e1126ac to your computer and use it in GitHub Desktop.
#include <iostream>
template< char FIRST, char... REST > struct binary
{
static_assert( FIRST == '0' || FIRST == '1', "invalid binary digit" ) ;
enum { value = ( ( FIRST - '0' ) << sizeof...(REST) ) + binary<REST...>::value } ;
};
template<> struct binary<'0'> { enum { value = 0 } ; };
template<> struct binary<'1'> { enum { value = 1 } ; };
// raw literal operator
template< char... LITERAL > inline
constexpr unsigned int operator "" _b() { return binary<LITERAL...>::value ; }
// raw literal operator
template< char... LITERAL > inline
constexpr unsigned int operator "" _B() { return binary<LITERAL...>::value ; }
int main()
{
// 10101 in binary is 21
std::cout << 10101_B << "\n";
// 011011000111 in binary is 1735
std::cout << 011011000111_b << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment