Created
November 16, 2025 06:44
-
-
Save airled/701fa825cbb437ef30e7bf8473278fb6 to your computer and use it in GitHub Desktop.
Represent u128 to the string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const ALPHABET: [char; 16] = | |
| ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; | |
| // Do not use in production: | |
| // - does not check base 0 | |
| // - u128 instead of generic | |
| // - no negative support | |
| fn to_s(num: u128, base: u128) -> String { | |
| let mut buffer: String = String::new(); | |
| let mut div = num; | |
| let mut rem = 0; | |
| loop { | |
| (div, rem) = (div / base, div % base); | |
| buffer.push(ALPHABET[rem as usize]); | |
| if div == 0 { break; } | |
| } | |
| buffer.chars().rev().collect() | |
| } | |
| fn main() { | |
| let s = to_s(255, 16); | |
| println!("{:?}", s); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment