This crate adds a tool to format a number in an arbitrary base from 2 to 36.
This is a light crate, without any dependency.
For primitive signed integers (i8
to i128
, and isize
), negative
values are formatted as the two’s complement representation.
There is also one specific function for each radix that does not
already exists in the standard library, e.g. radix_3
to format a number in base 3.
Get started
Add the crate in the cargo manifest:
= "1"
Import radix
in scope,
and you are ready to go:
use radix;
Examples
use *;
let n = 35;
// Ouput: "z"
println!;
// Same ouput: "z"
println!;
You can use the alternate modifier to capitalize the letter-digits:
use radix;
let n = 35;
// Ouput: "Z"
println!;
FAQ
-
Which digits are used when the base is superior to
10
?This crate uses the letters in alphabetic order. That is why the maximum base is 36: it uses all the digits and all the letters of the alphabet.
-
Among the functions that format in a specific base, why are some missing? For example there are
radix_7
andradix_9
, but notradix_8
.All the numbers in range
[2, 36]
are represented except2
,8
,10
and16
because they already exist in the standard library through binary, octal, decimal (regular) and hexadecimal formatting. -
What if I want to use the capitalized letters as digits?
Use the alternate modifier
{:#}
. -
Why does the formatting of negative numbers give a weird result?
Just as in the standard library, when a number is formatted in a non-decimal base, the two’s complement representation is used. That means that the number is casted to the unsigned version (for example, for an
i8
the following number is used:n as u8
).