Converts a decimal integer to the given base (2 to 36). Digits above 9 are written A, B, C … . The binary, octal and hexadecimal forms are also shown.
Explanation
This converts a decimal integer into any base from 2 to 36.
In base n every digit carries a weight that is a power of n, just as the decimal system we use every day weights its digits by powers of ten. In binary those weights are powers of two.
255=1×27+1×26+⋯+1×20 The method is mechanical: divide by the base, note the remainder, divide the quotient again. Keep going until the quotient reaches 0, then read the remainders from the bottom up.
- Decimal — the integer to convert, 0 or more
- Base — an integer from 2 to 36
- Digits above 9 are written A, B, C and so on; in hexadecimal F stands for 15
Example
Convert decimal 255 to binary. Dividing by 2 leaves a remainder of 1 every single time, and after eight steps the quotient hits 0. Reading the remainders from the bottom up gives
255(10)=11111111(2) Since 255=256−1=28−1, the answer is exactly eight 1s. The same number is 377 in octal and FF in hexadecimal.
Notes
- The base must be an integer from 2 to 36. Ten digits plus twenty-six letters give only 36 distinct symbols, which is where the upper limit comes from.
- The input must be a whole number of 0 or more. Negatives and decimals are not handled.
- One hexadecimal digit maps to exactly four binary digits. Split FF into 1111 1111 and the correspondence is easy to see, which is why hexadecimal is such a convenient shorthand for binary.
- More digits does not mean a bigger number. The smaller the base, the more digits the same value needs.