Spunk Odds Reference

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.

Four ranks from one digest (server seed sun-srv-5d0b, client seed sun-client-x, nonce 5)
DrawHex bytesAs integerFloatRank
17bb010192,075,136,0250.483155267
2ce98fe9b3,466,133,1470.8070220111
3fa7d12d84,202,500,8240.9784709713
44f2830e11,328,034,0170.309207015

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.

Chance of a given rank under two mappings, against the ideal 1/13
MappingFavored rankOther rankIdeal
One byte, value mod 137.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.