-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
hexadecimal_to_binary.rs
67 lines (60 loc) · 1.9 KB
/
hexadecimal_to_binary.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
57
58
59
60
61
62
63
64
65
66
67
// Author : cyrixninja
// Hexadecimal to Binary Converter : Converts Hexadecimal to Binary
// Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal
// 2. https://en.wikipedia.org/wiki/Binary_number
// Other References for Testing : https://www.rapidtables.com/convert/number/hex-to-binary.html
pub fn hexadecimal_to_binary(hex_str: &str) -> Result<String, String> {
let hex_chars = hex_str.chars().collect::<Vec<char>>();
let mut binary = String::new();
for c in hex_chars {
let bin_rep = match c {
'0' => "0000",
'1' => "0001",
'2' => "0010",
'3' => "0011",
'4' => "0100",
'5' => "0101",
'6' => "0110",
'7' => "0111",
'8' => "1000",
'9' => "1001",
'a' | 'A' => "1010",
'b' | 'B' => "1011",
'c' | 'C' => "1100",
'd' | 'D' => "1101",
'e' | 'E' => "1110",
'f' | 'F' => "1111",
_ => return Err("Invalid".to_string()),
};
binary.push_str(bin_rep);
}
Ok(binary)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_string() {
let input = "";
let expected = Ok("".to_string());
assert_eq!(hexadecimal_to_binary(input), expected);
}
#[test]
fn test_hexadecimal() {
let input = "1a2";
let expected = Ok("000110100010".to_string());
assert_eq!(hexadecimal_to_binary(input), expected);
}
#[test]
fn test_hexadecimal2() {
let input = "1b3";
let expected = Ok("000110110011".to_string());
assert_eq!(hexadecimal_to_binary(input), expected);
}
#[test]
fn test_invalid_hexadecimal() {
let input = "1g3";
let expected = Err("Invalid".to_string());
assert_eq!(hexadecimal_to_binary(input), expected);
}
}