Building Your Own Efficient uint128 in C++

https://news.ycombinator.com/rss Hits: 5
Summary

TL;DR: We build a minimal u128 as two u64 limbs and implement arithmetic using carry, borrow, and multiply intrinsics that map directly to x64 instructions. The generated code is on par with builtin __uint128_t for addition, subtraction, multiplication, and comparison. This is unsigned-only, x64-focused, and intentionally narrow in scope. The result is a solid foundation for exact, fixed-width arithmetic with a focus on good codegen and predictability, not abstraction. Full code and compiler output: https://godbolt.org/z/K6dn3s91Y Scope We take the smallest reasonable definition of a 128-bit integer, two 64-bit words, and turn it into a usable arithmetic type whose generated code is indistinguishable from a builtin __uint128_t. This post is explicitly not about dynamically-sized big integer arithmetic. It is about being explicit with range bounds and letting the compiler emit the exact instructions we want. The scope is deliberately limited: unsigned arithmetic, fixed width, modern x64, with Clang and GCC as the primary targets and notes for MSVC where it differs. Why fixed-width big integers In many domains, especially geometry and numerics, we do not need arbitrary precision. We need enough precision to be exact for known bounds, and we need the cost to be predictable. Dynamic big integer libraries solve a different problem. They are flexible and general, but they pay for that generality in memory traffic, branches, and indirection. If your values fit into a fixed number of bits and you know that ahead of time, fixed-width arithmetic is usually the better trade. (In fact, our high-performance exact mesh booleans are completely built on this: Exact Arithmetic in Solidean) A 128-bit integer is the gateway drug to fixed-width arithmetic. It is the smallest width that is no longer builtin, while still mapping cleanly to the underlying hardware. Once the carry and multiply patterns are explicit at 128 bits, extending them to 192 or 256 bits is straightforward. In produ...

First seen: 2026-02-01 23:31

Last seen: 2026-02-02 04:32