# What is SWAR (broadword computing)?

> SWAR (SIMD within a register), which Knuth calls broadword computing, treats a 64-bit word as many small fields at once. Popcount and friends.

**SWAR (broadword computing)**: SWAR, SIMD within a register, is the technique of using ordinary integer instructions on a full machine word to operate on many small packed fields at once; Knuth calls it broadword computing.

**SWAR**, "SIMD within a register", treats one 64-bit integer as eight bytes or sixteen 4-bit fields and works on all of them with a few plain adds, shifts and masks. Knuth calls it **broadword computing** and devotes much of Volume 4A's [§7.1.3](https://cracked.guide/guide/knuth-w105-0) to it.

## The classic example: popcount

Counting the 1 bits in a word (sideways addition) without a loop: add adjacent bits in pairs, then adjacent pairs in 4-bit fields, then bytes, using masks like `0x5555...` and `0x3333...` so the partial sums never overflow into each other. A final multiply gathers the byte sums into the top byte. Six or so instructions replace a 64-step loop.

## What else it does

Finding the lowest or highest set bit, testing whether any byte of a word is zero (how fast `strlen` works), reversing bits, packing and unpacking fields, and branch-free comparisons. [Part 2 of §7.1.3](https://cracked.guide/guide/knuth-w106-0) goes further, into broadword algorithms and their lower bounds. Many of these tricks now exist as single CPU instructions, but the reasoning carries over to every place you pack data tightly.

## Questions

### Is SWAR still useful with real SIMD instructions?

Yes. It needs no special instructions, works in any language with 64-bit integers, and the same ideas apply inside SIMD lanes.

---

Source: https://cracked.guide/glossary/swar
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
