Search code examples
c++11binarydecimalc++14user-defined-literals

How to compose and form the binary literals, for example through the conversion from decimal in C++11 / C++14?


int main() {
  int x = 3613;
  std::cout << "x= " << x << std::endl;
  std::string xBin = std::bitset<16>(x).to_string();
  std::cout << xBin << std::endl;
  unsigned long xDecimal = std::bitset<16>(xBin).to_ulong();
  std::cout << xDecimal << std::endl;
  std::cout << std::endl << std::endl;
  int b01 = 0b11001;
  std::cout << "b01= " << b01 << std::endl;
  int b02 = 0b1010;
  std::cout << "b02= " << b02 << std::endl;
  int b03 = b01 + b02;
  std::cout << "int b03 = b01 + b02 = " << b03 << std::endl;
  return 0;
}

Output:

x= 3613
0000111000011101
3613

 b01= 25
 b02= 10
 int b03 = b01 + b02 = 35

With binary literals we can do normal arithmetic operations, while with the strings obtained with std::bitset<> this is not possible. So...the question is: how to "compose" the binary literals, for example through the conversion from decimal to binary as obtained using std::bitset<> ? Looking forward to your kind help. Marco


Solution

  • You shouldn't operate on bitsets by converting them to string and back - that's missing the point of bitsets... Instead you operate on them by using binary operators: &, |, ^, ... (just like you would on usual integers).

    std::cout << std::bitset<3>(4) << " or "
              << std::bitset<3>(2) << " = "
              << (std::bitset<3>(4) | std::bitset<3>(2)) << std::endl;
    

    Prints: 100 or 010 = 110

    You can find all operators on wiki: http://en.cppreference.com/w/cpp/utility/bitset