Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 171 ยท Utilities

Numeric Limits, Complex Numbers and Bit Manipulation

Query type limits with std::numeric_limits, compute with std::complex, use the C++20 <bit> functions popcount, bit_width and rotl, and reinterpret bits safely with std::bit_cast.

Numbers in C++ are close to the hardware: an int has a fixed number of bits, a double has limited precision, and bits can be shifted and counted directly. To write correct numeric code you need to ask the types about their limits instead of hard-coding 2147483647 or 1e-9. You also need the right tools when the math leaves the real numbers or drops down to individual bits.

This lesson brings together four standard utilities: std::numeric_limits from <limits>, which describes every arithmetic type; std::complex from <complex>, for complex arithmetic; the C++20 <bit> header, with fast, portable bit operations; and std::bit_cast, the safe way to look at an object's raw bits. The Fundamental Data Types, Integer Types and Floating-Point Numbers lessons introduced the types; here you'll go deeper.

std::numeric_limits: asking a type about itself

std::numeric_limits<T> is a class template with a specialization for every arithmetic type. All of its members are static constexpr, so you can use them at compile time, in static_assert and as template arguments. The most useful members:

Member Meaning
max() largest finite value
lowest() most negative finite value (C++11)
min() smallest value for integers, but the smallest positive normal value for floating point
digits bits of precision (mantissa bits + 1 for floats, value bits for integers)
digits10 decimal digits that always survive a round trip text โ†’ type โ†’ text
max_digits10 decimal digits needed to print a floating-point value so it reads back exactly
epsilon() gap between 1.0 and the next representable value
infinity(), quiet_NaN() special floating-point values (check has_infinity, has_quiet_NaN)
is_signed, is_integer, is_iec559 properties; is_iec559 means IEEE 754 floating point
C++ What numeric_limits reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The classic bug: initializing "the largest value seen so far" with std::numeric_limits<double>::min(). That's a tiny positive number (about 2.2 ร— 10-308), so a list of all-negative values never beats it. Use lowest() (or -infinity()), or better, initialize from the first element or use std::ranges::max.

signed char prints as a number here because std::format formats signed char and unsigned char as integers; plain char would print as a character.

Using limits for safe arithmetic

Limits are most valuable when you're about to cross them. Signed overflow is undefined behavior, so you must check before the operation, not after. And comparisons between signed and unsigned values silently convert the signed side, so -1 < 1u is false. C++20 added helpers for exactly this:

  • std::cmp_less(a, b), std::cmp_equal, std::cmp_greater (and friends) in <utility> compare any two integers by their mathematical values.
  • std::in_range<T>(value) tells you whether value fits in type T.

For floating point, epsilon() is the building block for tolerant comparisons, and max_digits10 is how many digits you must print to save a double as text without losing anything.

C++ Overflow checks and safe comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The example spells out the conversion with static_cast<unsigned> because writing negative < positive directly triggers a -Wsign-compare warning, which is the compiler pointing at exactly this bug. Either way, -1 turns into 4294967295 and the comparison says false. std::cmp_less gets the mathematically correct answer with no cast and no warning.

GCC and Clang also offer __builtin_add_overflow(a, b, &result) and friends, which check overflow using the CPU's flags. C++26 standardizes the same idea as std::ckd_add, std::ckd_sub and std::ckd_mul in <stdckdint.h> (borrowed from C23).

Complex numbers with std::complex

std::complex<T> (for float, double or long double) represents a number a + bi. All arithmetic operators work, as do mixed operations with real numbers. With using namespace std::complex_literals; you can write imaginary literals like 2.0i (a complex<double>) or 2.0if (complex<float>).

The free functions cover the usual math:

  • real(z), imag(z): the parts (also members z.real(), z.imag()).
  • abs(z): the magnitude |z|; norm(z): the squared magnitude (cheaper, no square root); arg(z): the angle in radians.
  • conj(z): the conjugate; std::polar(r, theta): builds a number from magnitude and angle.
  • exp, log, pow, sqrt, sin, cos and the rest, all defined for complex arguments.

std::format can't print std::complex until C++26, so print the parts yourself (a tiny helper does it).

C++ Complex arithmetic and quadratic roots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice sqrt(-9.0) on a plain double gives NaN (printed as -nan here, because the NaN's sign bit happens to be set), while the complex version gives 0+3i. The real-number functions never switch to complex results on their own. Euler's identity prints a tiny imaginary part (around 10-16) instead of exactly zero, because ฯ€ itself can't be stored exactly.

Complex numbers make some algorithms beautifully short. The Mandelbrot set is the set of points c for which repeating z = zยฒ + c, starting at 0, never escapes to infinity:

C++ The Mandelbrot set in ASCII

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop compares std::norm(z) <= 4.0 instead of std::abs(z) <= 2.0: same test, no square root. Using norm in hot loops is a standard trick.

The <bit> header (C++20)

Bit manipulation used to mean compiler-specific intrinsics such as __builtin_popcount. C++20's <bit> provides portable functions that compile to single CPU instructions where available. They accept unsigned integer types only, which avoids the sign-bit surprises of signed shifts.

Function Returns For 0b0010'1100 (44)
std::popcount(x) number of 1 bits 3
std::countl_zero(x) / countl_one leading 0s / 1s 2 (for an 8-bit type)
std::countr_zero(x) / countr_one trailing 0s / 1s 2
std::bit_width(x) bits needed to store x 6
std::has_single_bit(x) is x a power of two? false
std::bit_floor(x) / bit_ceil(x) nearest power of two below / above 32 / 64
std::rotl(x, s) / rotr(x, s) rotate bits left / right
std::byteswap(x) (C++23) reverse byte order
std::endian::native endian::little or endian::big
C++ Counting, rounding and rotating bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

bit_width(n) - 1 is the integer base-2 logarithm, and bit_ceil rounds a size up to a power of two, which hash tables and allocators love. For named flags rather than raw masks, std::bitset and bitwise operators are more readable.

std::bit_cast: reinterpreting bits safely (C++20)

Sometimes you need the exact bit pattern of an object, for example to inspect how a float is stored, hash it, or send it over a network. The old tricks are both broken:

  • *reinterpret_cast<std::uint32_t*>(&f) violates the strict aliasing rule: reading an object through a pointer to an unrelated type is undefined behavior, and optimizers really do break such code.
  • Writing one member of a union and reading another is allowed in C but undefined behavior in C++.

std::bit_cast<To>(from) copies the bits of from into a new object of type To. Both types must have the same size and be trivially copyable; otherwise it doesn't compile. It's also constexpr, and compiles to a plain register move.

C++ Taking a float apart with bit_cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows the IEEE 754 layout: one sign bit, eight exponent bits stored with a bias of 127, and 23 mantissa bits with an implicit leading 1. 0.1f has a long, repeating mantissa, which is the bit-level reason why 0.1 can't be stored exactly. The Floating-Point Numbers lesson explains the consequences.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is std::numeric_limits<double>::min()?

    For floating-point types min() is the smallest positive normal value. Use lowest() for the most negative finite value.
  2. 2. What does std::cmp_less(-1, 1u) return?

    cmp_less compares the mathematical values, so -1 is less than 1. The plain expression -1 < 1u converts -1 to a huge unsigned value and gives false.
  3. 3. Which expression gives the squared magnitude of a std::complex<double> z without computing a square root?

    norm(z) returns realreal + imagimag. abs(z) is its square root, arg(z) is the angle, and conj(z) flips the sign of the imaginary part.
  4. 4. For std::uint32_t n = 40;, what does std::bit_ceil(n) return?

    bit_ceil returns the smallest power of two that is greater than or equal to n. bit_floor(40) would be 32 and bit_width(40) is 6.
  5. 5. Why is std::bit_cast preferred over reinterpret_cast for reading a float's bits?

    bit_cast copies the object representation into a new object, which is defined behavior. It requires equal sizes and trivially copyable types.

Summary

  • std::numeric_limits<T> describes every arithmetic type at compile time: max(), lowest(), digits, epsilon(), infinity(), max_digits10 and more. For floating point, min() is the smallest positive value, so use lowest() for the most negative.
  • Check for signed overflow before computing; compare mixed signed/unsigned values with std::cmp_less and friends, and check conversions with std::in_range.
  • std::complex<double> supports all arithmetic plus abs, norm, arg, conj, polar, exp and sqrt; 2.0i literals come from std::complex_literals.
  • <bit> gives portable popcount, countl_zero, countr_zero, bit_width, bit_ceil, rotl, byteswap and std::endian, for unsigned types.
  • std::bit_cast reinterprets the bits of a trivially copyable object as another type of the same size, safely and even at compile time.

Next: Threads, where you'll start running code concurrently with std::thread and std::jthread.