Learning Hub Search Ctrl K

Modern C++ › C++14

Binary Literals and Digit Separators

0b1010 and 1'000'000.

Since C++14 beginner #binary-literals#digit-separators#user-defined-literals#chrono-literals#string-literals

Explanation

C++14 makes numeric code more readable with two small additions:

  • Binary literals: prefix 0b or 0B: 0b1010'0101. Ideal for bit masks and hardware registers.
  • Digit separators: the apostrophe ' may appear between digits (any number of times, any grouping) and is ignored: 1'000'000, 0xFF'EC'DE'5E, 3.141'592'653.

C++14 also adds standard literal suffixes (built on the C++11 user-defined literal mechanism) in the namespaces std::literals:

Header Suffixes Example
<chrono> h min s ms us ns 150ms, 2h
<string> s "text"s is a std::string
<complex> i if il 3.0 + 2i

You can define your own: constexpr Meters operator""_m(long double v) { return Meters(v); }.

Example

#include <chrono>
#include <iostream>
#include <string>

using namespace std::literals;                         // brings in s, ms, h, ...

struct Meters {
    long double value;
};
constexpr Meters operator""_m(long double v) { return Meters{v}; }
constexpr Meters operator""_km(long double v) { return Meters{v * 1000}; }

int main() {
    unsigned flags = 0b0000'1010;                      // binary with a nibble separator
    long population = 7'900'000'000;
    double pi = 3.141'592'653;
    unsigned mask = 0xFF00'FF00;
    std::cout << flags << " " << population << " " << pi << " " << std::hex << mask << std::dec << "\n";

    flags |= 0b0100;                                   // set a bit by literal
    std::cout << flags << "\n";                        // 14

    auto name = "widget"s;                             // std::string, not const char*
    std::cout << name.size() << "\n";                  // 6

    auto timeout = 1500ms;
    std::cout << std::chrono::duration_cast<std::chrono::seconds>(timeout).count() << "\n";   // 1
    std::cout << (2h + 30min).count() << "\n";         // 150 (minutes)

    Meters d = 2.5_km;
    std::cout << static_cast<double>(d.value) << "\n"; // 2500
    return 0;
}

Common pitfalls

  • A separator cannot be first, last, or next to the base prefix: '100, 100', 0x'FF are errors.
  • Separators have no semantic meaning, so 1'0 is just 10; don’t use them to mislead.
  • User-defined literal suffixes without a leading underscore are reserved for the standard library.
  • "text"s needs using namespace std::literals (or std::string_literals); without it the suffix is unknown.
  • 0b literals aren’t in C++11; older compilers accepted them as an extension, but they were not portable until C++14.

Legacy vs modern

C++98 expressed bit patterns in hex/octal (0x0A) or with macros, and std::string("x") or std::chrono::milliseconds(1500) for typed values. C++23 adds more literal suffixes (e.g. uz for size_t).

Exercises

1. Write the number one billion using digit separators.

1'000'000'000