Integer to Sortable String Converter
Convert integers to lexicographically sortable strings (lexinum format). Pack, unpack, and batch-sort positive and negative numbers for LevelDB keys and sorted arrays.
| # | Packed String | Unpacked Integer |
|---|
About
Lexicographic ordering treats numeric strings as text. The value 9 sorts after 10 because the character 9 > 1. Key-value stores like LevelDB and JavaScript's native Array.sort() both default to this behavior. Storing raw integers as keys produces silently wrong iteration order - a defect that surfaces only under load and is expensive to debug. This tool implements the lexinum packing scheme: each integer is floored, its absolute value is zero-padded to 16 digits (covering up to 253), and prefixed with P or N. Negative values undergo a nines-complement transformation so that −100 sorts before −1, matching true numeric order. Non-integer floats are truncated. Values outside the safe integer range (±9007199254740992) will produce incorrect results because JavaScript loses precision beyond 253.
Formulas
The packing algorithm converts an integer n into a fixed-width string that preserves numeric order under lexicographic comparison.
pack(n) =
Where pad(v, w) left-pads the decimal string of v with zeros to width w = 16 (the digit count of 253 = 9007199254740992).
The nines-complement function replaces each digit d with 9 − d. This reverses the sort order within the N-prefixed group so that larger absolute values (more negative numbers) produce lexicographically smaller strings.
The unpack operation reverses the process: strip the prefix character, apply complement if N, parse to integer, and restore the sign.
Where n = input integer, w = pad width (16), d = individual digit, s = padded digit string.
Reference Data
| Integer Input | Packed String | Sort Position (among examples) |
|---|---|---|
| −9007199254740992 | N0000000000000000 | 1 (smallest) |
| −1000000 | N8999999999000000 | 2 |
| −9999 | N9999999999990000 | 3 |
| −100 | N9999999999999899 | 4 |
| −10 | N9999999999999989 | 5 |
| −1 | N9999999999999998 | 6 |
| 0 | P0000000000000000 | 7 |
| 1 | P0000000000000001 | 8 |
| 10 | P0000000000000010 | 9 |
| 100 | P0000000000000100 | 10 |
| 9999 | P0000000000009999 | 11 |
| 1000000 | P0000000001000000 | 12 |
| 9007199254740992 | P9007199254740992 | 13 (largest) |
| 3.14 (float) | P0000000000000003 (floored) | - |
| −7.99 (float) | N9999999999999992 (floored to −7) | - |