Does Rust have a set of functions that make converting a decimal integer to a hexadecimal string easy? I have no trouble converting a string to an integer, but I can't seem to figure out the opposite. Currently what I have does not work (and may be a bit of an abomination)
Editor's note - this code predates Rust 1.0 and no longer compiles.
pub fn dec_to_hex_str(num: uint) -> String { let mut result_string = String::from_str(""); let mut i = num; while i / 16 > 0 { result_string.push_str(String::from_char(1, from_digit(i / 16, 16).unwrap()).as_slice()); i = i / 16; } result_string.push_str(String::from_char(1, from_digit(255 - i * 16, 16).unwrap()).as_slice()); result_string }
Am I on the right track, or am I overthinking this whole thing?
Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.
Hex encoding is performed by converting the 8 bit data to 2 hex characters. The hex characters are then stored as the two byte string representation of the characters. Often, some kind of separator is used to make the encoded data easier for human reading.
HEX values greater than 80000000 represent negative integer values. Hex value FFFFFFFF represents the integer value -1.
You’re overthinking the whole thing.
assert_eq!(format!("{:x}", 42), "2a"); assert_eq!(format!("{:X}", 42), "2A");
That’s from std::fmt::LowerHex
and std::fmt::UpperHex
, respectively. See also a search of the documentation for "hex".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With