Bit Grouping (5-bit chunks)
Bit Grouping: The 5-Bit Transformation
The core mathematical engine of Bech32 is the conversion of standard 8-bit bytes into 5-bit chunks. This process is often called "Squashing" or "Bit Grouping."
1. The 8-to-5 Problem
Computers store data in bytes (8 bits). However, the Bech32 alphabet only has 32 characters, which can only represent 5 bits of information ($2^5 = 32$).
-
To encode a 20-byte hash into Bech32, we must take the 160 bits (20 bytes $\times$ 8) and redistribute them into groups of 5.
-
Total Groups: $160 \div 5 = 32$ groups.
2. The Conversion Process
Imagine we have three bytes (24 bits): 11111111 00000000 10101010.
To convert to 5-bit chunks, we simply regroup them:
-
11111(Group 1) -
11100(Group 2) -
00000(Group 3) -
01010(Group 4) -
1010?(Group 5 - needs padding)
3. Padding
Since the total number of bits might not be a perfect multiple of 5, the algorithm adds zero-bits at the end to complete the final 5-bit group.
-
If we have 160 bits, it divides perfectly (32 groups).
-
If we have a Taproot hash (256 bits), $256 \div 5 = 51$ with a remainder of 1. We would need 52 groups to hold all the data.
4. Why this is efficient?
Because 5 and 8 are both small integers, this bit-shifting can be done using simple bitwise operators (\u003c\u003c, \u003e\u003e, \u0026).
-
Unlike Base58, which requires "BigInteger" division (calculating values across the entire 20-byte string at once), Bech32 can be processed 1 byte at a time.
-
This makes Bech32 ideal for low-power devices like hardware wallets and embedded systems.
| Data Type | Bit Count | 5-Bit Groups |
|---|---|---|
| PK Hash | 160 Bits | 32 Groups |
| Script Hash | 256 Bits | 52 Groups |
| Taproot Key | 256 Bits | 52 Groups |
In the final section, we will build a Python Bech32 Auditor.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: