41

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?

2
  • 2
    Incidentally, string.push_str(String::from_char(1, char).as_slice()) is impressively inefficient; to do something like that, string.push_char(char) is what you should do. Commented Jul 29, 2014 at 3:46
  • 1
    @ChrisMorgan thanks for the pointer, I'm very new to rust coming from c++ and know some of the concepts i'm using are bad. Commented Jul 29, 2014 at 3:50

1 Answer 1

104

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".

Sign up to request clarification or add additional context in comments.

1 Comment

@10cls: as_slice was just for getting the &str out of the String so you could compare it with a string slice. assert_eq! has changed now so that you don’t even need & or &* as in &*format!(…).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.