# This Trick Computes Leading Zeros with One Floating-Point Subtraction

Original title: Vectorized CLZ and CTZ

> Hacker News story 50039608 · language: en · submitted 2026-10-11
> Web version: https://zeli.app/story/50039608
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 65 · by [zX41ZdbW](<https://news.ycombinator.com/user?id=zX41ZdbW>) · 💬 5
[original](<https://purplesyringa.moe/blog/vectorized-clz-and-ctz/>) · [HN discussion](<https://news.ycombinator.com/item?id=50039608>)

## Summary

A clever floating-point hack computes clz and ctz without dedicated instructions. By embedding an integer into the mantissa of a double and subtracting, you can extract the leading-zero count from the exponent. The vectorized version runs at 0.45 ns per iteration on Haswell, beating the scalar 1 ns. For ctz, a similar trick isolates the lowest set bit. A de Bruijn sequence approach offers higher throughput, and a 64-bit variant using pshufb and psadbw handles ctz(0)=64 correctly.

## Key quote

> Floating-point exponents are biased logarithms of their values. By substituting a 32-bit number x into the mantissa of some value 2^k, we get a double representing 2^k (1 + 2^-52 x). We can then subtract 2^k as a double to get 2^(k-52) x. Extracting the exponent gives k - 52 + 31 - clz(x), from which clz can be computed with a bitwise subtraction.

## HN discussion (5 comments)

### [wahern](<https://news.ycombinator.com/item?id=50051342>)

> Pretty cool that they seemed to have come up with the idea on their own, but they're definitely not the first: https://graphics.stanford.edu/~seander/bithacks.html#ZerosOn...

### [jandrewrogers](<https://news.ycombinator.com/item?id=50050518>)

> This is a good illustration of what competent SIMD code requires.

### [saagarjha](<https://news.ycombinator.com/item?id=50050527>)

> Might be useful on a GPU or something I guess?

---

## Cite

- Page: https://zeli.app/story/50039608
- Date: 2026-10-11
- Source: purplesyringa.moe (https://purplesyringa.moe/blog/vectorized-clz-and-ctz/)
- Hacker News: https://news.ycombinator.com/item?id=50039608

## Other languages

- zh: https://zeli.app/zh/story/50039608 · markdown: https://zeli.app/zh/story/50039608.md
- ja: https://zeli.app/ja/story/50039608 · markdown: https://zeli.app/ja/story/50039608.md
- ko: https://zeli.app/ko/story/50039608 · markdown: https://zeli.app/ko/story/50039608.md
- de: https://zeli.app/de/story/50039608 · markdown: https://zeli.app/de/story/50039608.md
- es: https://zeli.app/es/story/50039608 · markdown: https://zeli.app/es/story/50039608.md
- ru: https://zeli.app/ru/story/50039608 · markdown: https://zeli.app/ru/story/50039608.md
