File tree 1 file changed +67
-0
lines changed
1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Author : cyrixninja
2
+ // Hexadecimal to Binary Converter : Converts Hexadecimal to Binary
3
+ // Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal
4
+ // 2. https://en.wikipedia.org/wiki/Binary_number
5
+ // Other References for Testing : https://www.rapidtables.com/convert/number/hex-to-binary.html
6
+
7
+ fn hexadecimal_to_binary ( hex_str : & str ) -> Result < String , String > {
8
+ let hex_chars = hex_str. chars ( ) . collect :: < Vec < char > > ( ) ;
9
+ let mut binary = String :: new ( ) ;
10
+
11
+ for c in hex_chars {
12
+ let bin_rep = match c {
13
+ '0' => "0000" ,
14
+ '1' => "0001" ,
15
+ '2' => "0010" ,
16
+ '3' => "0011" ,
17
+ '4' => "0100" ,
18
+ '5' => "0101" ,
19
+ '6' => "0110" ,
20
+ '7' => "0111" ,
21
+ '8' => "1000" ,
22
+ '9' => "1001" ,
23
+ 'a' | 'A' => "1010" ,
24
+ 'b' | 'B' => "1011" ,
25
+ 'c' | 'C' => "1100" ,
26
+ 'd' | 'D' => "1101" ,
27
+ 'e' | 'E' => "1110" ,
28
+ 'f' | 'F' => "1111" ,
29
+ _ => return Err ( "Invalid" . to_string ( ) ) ,
30
+ } ;
31
+ binary. push_str ( bin_rep) ;
32
+ }
33
+
34
+ Ok ( binary)
35
+ }
36
+
37
+ #[ cfg( test) ]
38
+ mod tests {
39
+ use super :: * ;
40
+
41
+ #[ test]
42
+ fn test_empty_string ( ) {
43
+ let input = "" ;
44
+ let expected = Ok ( "" . to_string ( ) ) ;
45
+ assert_eq ! ( hexadecimal_to_binary( input) , expected) ;
46
+ }
47
+
48
+ #[ test]
49
+ fn test_hexadecimal ( ) {
50
+ let input = "1a2" ;
51
+ let expected = Ok ( "000110100010" . to_string ( ) ) ;
52
+ assert_eq ! ( hexadecimal_to_binary( input) , expected) ;
53
+ }
54
+ #[ test]
55
+ fn test_hexadecimal2 ( ) {
56
+ let input = "1b3" ;
57
+ let expected = Ok ( "000110110011" . to_string ( ) ) ;
58
+ assert_eq ! ( hexadecimal_to_binary( input) , expected) ;
59
+ }
60
+
61
+ #[ test]
62
+ fn test_invalid_hexadecimal ( ) {
63
+ let input = "1g3" ;
64
+ let expected = Err ( "Invalid" . to_string ( ) ) ;
65
+ assert_eq ! ( hexadecimal_to_binary( input) , expected) ;
66
+ }
67
+ }
You can’t perform that action at this time.
0 commit comments