Skip to content

Instantly share code, notes, and snippets.

@lichray
Created November 27, 2012 12:23
Show Gist options
  • Select an option

  • Save lichray/4153963 to your computer and use it in GitHub Desktop.

Select an option

Save lichray/4153963 to your computer and use it in GitHub Desktop.
User-defined binary literal in C++11
#include <iostream>
// http://stackoverflow.com/questions/537303/binary-literals
template<char... digits>
struct conv2bin;
template <char... digits>
constexpr int operator"" _b() {
return conv2bin<digits...>::value;
}
template <>
constexpr int operator"" _b<'0'>() {
return 0;
}
template <>
constexpr int operator"" _b<'1'>() {
return 1;
}
template<char high, char... digits>
struct conv2bin<high, digits...> {
static constexpr int value = operator"" _b<high>() <<
sizeof...(digits) ^ conv2bin<digits...>::value;
};
template<char high>
struct conv2bin<high> {
static constexpr int value = operator"" _b<high>();
};
int main() {
std::cout << 0_b << std::endl;
std::cout << 101_b << std::endl;
std::cout << 000111101_b << std::endl;
std::cout << 11111111111111111111111111111111_b << std::endl;
return 0;
}
@5tephenbennett

Copy link
Copy Markdown

Nice!

I referenced your work in my answer to "How to get smallest variable with C++11 user defined literals" here: https://stackoverflow.com/a/53702658/1353336

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment