Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal number to hexadecimal string

Tags:

rust

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?

like image 686
Syntactic Fructose Avatar asked Jul 29 '14 02:07

Syntactic Fructose


People also ask

How do you convert a decimal number to hexadecimal?

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.

How do I encode a hex string?

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.

What is Ffffffff in hexadecimal?

HEX values greater than 80000000 represent negative integer values. Hex value FFFFFFFF represents the integer value -1.


1 Answers

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

like image 162
Chris Morgan Avatar answered Sep 27 '22 22:09

Chris Morgan