Hi-lo guide
Sun Hi-lo: how hash bytes become a card
This address carries the name Sun for historical reasons only, and the hi-lo it describes is the ordinary kind. The question here is narrow and technical: how a string of hash bytes is turned into one of 13 card ranks, and how even that mapping really is.
Four bytes, one float
An HMAC-SHA256 digest is 32 bytes, shown as 64 hex digits. A common method takes the first 4 bytes (8 hex digits), reads them as an unsigned whole number between 0 and 2^32 - 1, and divides by 2^32 = 4,294,967,296. The result is a float u with 0 <= u < 1. The next 4 bytes give the next float, and so on, eight floats per digest.
| Draw | Hex bytes | As integer | Float | Rank |
|---|---|---|---|---|
| 1 | 7bb01019 | 2,075,136,025 | 0.48315526 | 7 |
| 2 | ce98fe9b | 3,466,133,147 | 0.80702201 | 11 |
| 3 | fa7d12d8 | 4,202,500,824 | 0.97847097 | 13 |
| 4 | 4f2830e1 | 1,328,034,017 | 0.30920701 | 5 |
Computed with Python's hmac and hashlib. Rank = floor(float x 13) + 1, with Ace = 1 and King = 13.
Floor of the float times 13
Multiplying u by 13 stretches the interval [0, 1) to [0, 13). Rounding down gives a whole number from 0 to 12, and adding 1 shifts it to 1 to 13. Each rank owns one thirteenth of the float range: rank 1 owns u below 1/13, rank 2 owns u from 1/13 up to 2/13, and so on.
Why it is nearly, not perfectly, even
The float is not continuous. It can only take 4,294,967,296 distinct values, and 13 does not divide that number. Dividing gives 330,382,099 with a remainder of 9. So 9 ranks receive 330,382,100 of the possible values and the other 4 receive 330,382,099. The favored ranks are more likely by a factor of about 1 + 1/330,382,099, a difference of roughly 3.0 parts per billion. No session of any realistic length could detect it.
The shortcut that is not even
Some code takes a single byte (0 to 255) and uses byte % 13. Here the remainder is large compared with the range: 256 = 19 x 13 + 9. Remainders 0 to 8 each get 20 byte values and the other 4 remainders get 19.
| Mapping | Favored rank | Other rank | Ideal |
|---|---|---|---|
| One byte, value mod 13 | 7.8125% | 7.4219% | 7.6923% |
| Four bytes, floor(float x 13) | 7.69230770% | 7.69230768% | 7.69230769% |
Exact counts of input values per rank, divided by the number of possible inputs.
With one byte, the favored ranks come up about 5.3% more often than the others. In hi-lo that would quietly move the true chance of every call away from the advertised one. Wider inputs, or rejecting the few input values above the largest multiple of 13, remove the problem.