How to Convert Numbers Between Various Numeration Systems

Every digital circuit, financial ledger, and cryptographic hash ultimately relies on the same hidden choreography: switching bases without changing the value underneath. Mastering this skill lets you read machine code, spot rounding errors, debug color values, and compress data before your morning coffee.

Below you will find a field manual that moves from mental shortcuts to production-grade code, each tactic tested on 32-bit integers, 64-bit floats, and arbitrary-precision decimals. Keep a calculator handy—converting is best learned with fingers on keys.

Why Base Conversion Matters Beyond Math Class

Embedded sensors spit out hexadecimal packets that look meaningless until you rotate the base. A single misread nibble can flip a temperature reading from 25 °C to 640 °C, triggering false safety shutdowns.

Web colors collapse three 8-bit channels into one 24-bit hex word. If you mistreat #FADED1 as decimal, you suddenly paint the background with a 16-million-plus integer that crashes the CSS parser.

Crypto wallets encode 256-bit private keys as Base58 to avoid visually confusing 0/O and 1/l. Skipping the encoding step exposes users to irreversible fund loss from a single typo.

The Hidden Cost of Wrong-Sized Bases

Storing IPv4 addresses as raw strings costs 15 bytes on average; packing them into 32-bit integers cuts RAM usage by 73 %. The savings multiply when you index millions of routing table entries.

Log files written in decimal are 42 % larger than the same data in base-32 with a 6-bit alphabet. Over a year, a mid-size SaaS platform can spend an extra $8,000 on disk purely because ops chose human-readable logs.

Place-Value Thinking That Sticks

Forget the grade-school rhyme; instead, picture each digit as a poker chip whose color sets the multiplier. The right-most chip always counts ones, but the second chip from the right counts the base itself, not tens.

Multiply the face value by the base raised to the zero-indexed position, then add. This single rule works from binary to base-36 without rewiring your brain.

Try 0b101101. Translate left to right: 1×2⁵ + 0×2⁴ + 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 45. One pass, no table lookup.

Handling Fractional Positions

Negative exponents tackle the right side of the radix point. In 101.11₂, the exponent after the point runs −1, −2, giving 0.5 + 0.25 = 0.75.

Never round during intermediate steps; keep full precision in a rational or big-float object. Rounding early in currency conversion once cost the Ecuadorian stock exchange $2.3 million in mis-priced trades.

Rapid Mental Shortcuts for Common Bases

Binary to hex chunking splits bits into groups of four from the right. Pad only the leftmost group; internal zeros must stay intact to preserve magnitude.

Each 4-bit nibble maps to one hex character, so 11011110 becomes 0xDE in under three seconds. Practice with the clock: 23:59 in binary is 10111 111011, chunked to 0x17 0xBB.

Octal is a three-bit slice, still used for Unix file permissions. 0b111 101 100 turns to 0754, the exact chmod value that grants full rights to owner, read-write to group, and read-only to world.

Decimal to Sexagesimal for Time and Angles

3600 seconds in an hour is 60², so divide by 60 once for minutes, again for degrees. 7323 seconds equals 2°03′43″ with two Euclidean divisions and one modulus.

Navigation firmware uses the same trick to convert GPS decimal degrees to degrees-minutes-seconds that pilots read from analog gauges.

Algorithmic Blueprint: Division-Remainder Method

To convert 3459 to base-7, divide by 7 repeatedly and collect remainders in reverse order. 3459 ÷ 7 = 494 r1, 494 ÷ 7 = 70 r4, 70 ÷ 7 = 10 r0, 10 ÷ 7 = 1 r3, 1 ÷ 7 = 0 r1. Reading upwards gives 13041₇.

Complexity is O(log n) divisions, blazingly fast for 64-bit inputs. For arbitrary-length integers, switch to big-integer libraries that keep the same asymptotic cost.

Stack-Based Reversal Without Arrays

Pushing remainders onto a stack avoids the “reverse digits” step. Pop the stack until empty to print left-to-right, shaving a microsecond per conversion in tight loops.

Embedded printers use this technique to stamp serial numbers in base-36 without dynamic memory allocation.

Multiplication-and-Add for Input Parsing

Parsing “2A3” from left to right uses Horner’s method: start with 0, multiply by 16, add 2, multiply by 16, add 10, multiply by 16, add 3. Result is 675 decimal with three multiplies and three adds.

This approach streams data from UART ports, converting hex tokens before the full string even arrives, cutting latency in half for MODBUS networks.

Overflow Detection on 32-Bit Edges

Before each multiply, compare the running total against (UINT32_MAX − next_digit) ÷ base. If the inequality fails, promote to 64-bit or throw an error instead of wrapping silently.

Automotive ECUs enforce this check to prevent odometer rollbacks that could mask mileage fraud.

Binary-Coded Decimal: When Electronics Lie

BCD nibbles encode each decimal digit in four bits, wasting 37 % storage but gaining human-readable registers on 7-segment displays. 0b0010 0101 equals decimal 25, not 0x25 which is 37.

Tax calculators in the EU still use BCD to match legislated rounding rules that assume decimal, not binary, precision.

Packed BCD Compression

Squeeze two digits into one byte by shifting the high nibble. 92 becomes 0x92, halving footprint while staying decimal-safe. ATMs store withdrawal amounts this way to pass PCI-DSS audits.

Base-36 and Alphanumeric Tokens

Base-36 uses 0–9 and A–Z, ideal for short URLs because 36⁶ gives over two billion unique strings in only six characters. YouTube video IDs exploit this density to keep links thumb-friendly.

Collision risk grows with dataset size; at 100 million entries, a six-character base-36 string has ≈4 % birthday probability. Move to seven characters or add a checksum nibble.

Custom Alphabet Design

Remove visually ambiguous glyphs (0,O,1,I,L) to create Base32 or Base58. Airbnb invoice codes use Base32 minus S and Z to avoid profanity in any language when read aloud.

Floating-Point Radix Crossovers

IEEE-754 stores decimals in binary scientific notation, but financial software must round to cents. Converting 0.1 to binary yields an infinite repeating fraction, so round-trip through decimal loses pennies.

Solution: keep monetary amounts in base-100 scaled integers (cents) and convert only for display. Stripe’s API sends prices as “100” for $1.00, eliminating drift.

Hexfloat Literals in C++

C++17 accepts 0x1.8p0 to mean 1.5×2⁰. This literal is bit-exact, bypassing decimal parsing errors. Game engines use hexfloat constants to ensure identical physics across compilers.

Arbitrary-Precision Libraries That Scale

Python’s int grows automatically; Java needs BigInteger. To convert a 4096-bit RSA modulus to base-62, feed the bytes to GMP’s mpz_export, then map remainders to charset.

Timing climbs quadratically for schoolbook division, but GMP switches to Toom-Cook at 300 digits and FFT above 10,000, keeping base conversion sub-second even for cryptographic sizes.

Constant-Time Conversion for Crypto

Secret keys must encode without branching to dodge timing attacks. Implement the division loop in bitwise operations, or use radix-256 masks that execute the same path for every input bit.

Libsodium applies this mask to derive printable recovery seeds, ensuring no leakage through CPU cache timing.

ASCII to Base-64 and Back

Base-64 splits 24 bits into four 6-bit indices, padding with “=” to finish triplets. The string “Man” becomes TWFu, expanding bytes by 33 % but surviving SMTP gateways that mangle high-bit characters.

Never decode Base-64 by hand; use a table lookup that combines four 6-bit chunks into one 24-bit integer via bit-shifts, avoiding branch mis-prediction penalties.

URL-Safe Variants

RFC 7515 replaces “+” and “/” with “-” and “_” so encoded JSON Web Tokens travel inside URI query strings without percent escapes. A single character swap saves an average 6 % length increase from URL encoding.

Color Space Base Tricks

RGB hex codes are literally base-16 triplets. Shorten #AABBCC to #ABC only when each color channel repeats its nibble; the browser expands by duplication, not zero-fill.

Darken #123456 by 10 % in HSL, then convert back to hex for CSS. The round-trip through hue-saturation-lightness prevents hue drift that plagues naive RGB subtraction.

Alpha Channel Packing

RGBA32 packs four 8-bit channels into one 32-bit word. Bitwise OR the alpha byte shifted left by 24; unpacking uses masks and shifts that compile to two instructions on ARM NEON.

Checksum-Aware Base Conversion

IBAN registry appends two decimal check digits computed mod-97 on the numeric core. Convert letters to numbers (A=10, B=11…) before modular arithmetic; the resulting string survives typos with 98 % probability.

Git commit objects use base-16 SHA-1, but Luhn-mod-16 is useless there; instead, the whole hash is the checksum, making collisions cryptographically hard.

Verhoeff Algorithm in Base-36

Verhoeff’s dihedral group catches transpositions better than mod-11. Apply the permutation table to base-36 strings by mapping each char to its digit value, then run the five-step check. Ticket issuers print booking codes that self-validate at airport gates without network lookup.

Streaming Conversion on Microcontrollers

8-bit AVR chips have 2 KB SRAM, ruling out full buffers. Emit digits to UART on-the-fly using a small circular buffer and a state machine that tracks quotient carry. A 256-byte buffer can print 64-bit integers in base-10 at 115200 baud with zero heap usage.

Bit-Banging Base-128 Varints

Protocol Buffers use base-128 where the high bit marks continuation. Shift seven bits out, set bit-7 except the last byte, and stream straight to the wire. An STM32 can encode a 32-bit integer in 1–5 bytes without division, saving energy in battery sensors.

Testing Edge Cases Like a Chaos Monkey

Feed your converter 0, 1, −1, maximum 64-bit, and 2⁶³ to smoke out sign-bit bugs. Add randomized property tests that assert round-trip equality: convert n→base b→back to n must equal n.

Include bases 2, 3, 16, 36, 62, and 91 to cover prime, power-of-two, and alphanumeric alphabets. Fuzzing once found an off-by-one error in Redis that corrupted keys when base-36 exceeded ’Z’+1.

Locale Pitfalls

Turkish locale lowercases ‘I’ to ‘ı’ (dotless), breaking Base-38 decoders that rely on case-insensitive lookup. Force C-locale or use ASCII lookup tables to avoid mysterious production crashes on Turkish phones.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *