I was chasing a mismatched ID in a log line last week. The value came in as hex, I pasted it into a converter, got a decimal back, compared it with what the database held — and the two disagreed by 4,095. The hex was fine. The converter was fine for 32-bit values. The number was 64 bits.
Here are the five traps I have hit often enough to check first every time.
1. Floats can't hold 64-bit integers
parseInt('FFFFFFFFFFFFFFFF', 16)
// 18446744073709552000 (wrong)
BigInt('0xFFFFFFFFFFFFFFFF').toString()
// '18446744073709551615' (right)
A JavaScript number is a binary64 float: 53 bits of integer precision. Number.MAX_SAFE_INTEGER is 9,007,199,254,740,991, and everything above it is rounded to the nearest representable value. Any hex ID, hash prefix, or snowflake ID past that boundary is silently wrong the moment it passes through parseInt, Number(), or JSON.parse.
2. Bitwise operators truncate to 32 bits
(2**32) | 0 // 0
(2**31) | 0 // -2147483648
|, &, >>, ~ squeeze both operands into signed 32-bit integers. Flag maths that works in tests fails on a value above 2^31, and it fails quietly — the result is still a number. Use BigInt with the n operators (&n, >>n) when you mean 64 bits.
3. Negative numbers have no canonical hex form
(-1).toString(16) // '-1'
(-1 >>> 0).toString(16) // 'ffffffff'
Both are "correct". One is a signed magnitude, the other is 32-bit two's complement; the same ciphertext differs if the other side assumes 64 bits (ffffffffffffffff). Whenever you convert a signed value, decide the width explicitly and write it down in the protocol.
4. parseInt changed meaning, and it stops at garbage
parseInt('08') is 8 and parseInt('010') is 10 — the legacy octal default disappeared in ES5. Octal now needs 0o or an explicit radix. The sibling trap: parseInt('12px') returns 12 while Number('12px') returns NaN. Lenient parsing turns a typo into a plausible ID.
5. Fractions are where conversions go feral
(255.5).toString(16) is 'ff.8', which looks sane. But (1234.567).toString(2) returns a 40-digit tail — you are looking at the binary expansion of a float, not the binary of 1234.567. Convert integers exactly and scale (cents, milliseconds, basis points) instead of converting fractions.
What helps
Convert integers only. Keep BigInt from input to output. Before copying a value anywhere, check how many bytes it needs: 1 byte covers 0–255, 2 covers 65,535, 4 covers 4,294,967,295. If a 5-byte value is in a field that the protocol says is 4 bytes, that is the bug, not the arithmetic.
For quick checks I use a number base converter that parses with BigInt, syncs decimal/hex/binary/octal in one view, and prints the minimum byte width plus the 32-bit and 64-bit unsigned forms of negatives. It runs entirely in the page — no upload, so it is safe for IDs pulled from production logs.
Most base bugs aren't arithmetic bugs. They're width bugs and precision bugs wearing an arithmetic costume.
Top comments (0)