-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathdecimal_to_hexadecimal.rs
56 lines (46 loc) · 1.15 KB
/
decimal_to_hexadecimal.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
pub fn decimal_to_hexadecimal(base_num: u64) -> String {
let mut num = base_num;
let mut hexadecimal_num = String::new();
loop {
let remainder = num % 16;
let hex_char = if remainder < 10 {
(remainder as u8 + b'0') as char
} else {
(remainder as u8 - 10 + b'A') as char
};
hexadecimal_num.insert(0, hex_char);
num /= 16;
if num == 0 {
break;
}
}
hexadecimal_num
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zero() {
assert_eq!(decimal_to_hexadecimal(0), "0");
}
#[test]
fn test_single_digit_decimal() {
assert_eq!(decimal_to_hexadecimal(9), "9");
}
#[test]
fn test_single_digit_hexadecimal() {
assert_eq!(decimal_to_hexadecimal(12), "C");
}
#[test]
fn test_multiple_digit_hexadecimal() {
assert_eq!(decimal_to_hexadecimal(255), "FF");
}
#[test]
fn test_big() {
assert_eq!(decimal_to_hexadecimal(u64::MAX), "FFFFFFFFFFFFFFFF");
}
#[test]
fn test_random() {
assert_eq!(decimal_to_hexadecimal(123456), "1E240");
}
}