Advertisement
zhangsongcui

bin2dec

Jan 30th, 2012
457
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. namespace util
  2. {
  3.     template <typename Ty, char N, char... Others>
  4.     struct bin2dec {
  5.         static_assert(N == '1' || N == '0', "Invaild binary number");
  6.         static constexpr Ty value = ( static_cast<Ty>(N - '0') << sizeof...(Others) ) + bin2dec<Ty, Others...>::value;
  7.     };
  8.  
  9.     template <typename Ty, char N>
  10.     struct bin2dec<Ty, N> {
  11.         static_assert(N == '1' || N == '0', "Invaild binary number");
  12.         static constexpr Ty value = static_cast<Ty>(N - '0');
  13.     };
  14. }
  15.  
  16. template <char... Nums>
  17. constexpr int operator "" _b() {
  18.     return util::bin2dec<int, Nums...>::value;
  19. }
  20.  
  21. int main() {
  22.     static_assert(0_b == 0, "");
  23.     static_assert(101010_b == 42, "");
  24.     static_assert(1111111_b == (1 << 7) - 1, "");
  25.     static_assert(11111111111111111111111111111111_b == -1, "");
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement