conversion/
conversion.rs

1use to_binary::BinaryString;
2
3fn main() {
4    hexadecimal();
5    str_func();
6    string();
7    vector();
8    byte();
9}
10
11fn hexadecimal() {
12    // Hex-Digest from Blake2b-128bits of "TEST"
13    let input_hex = "5AECF81369E312D6A3A92DD14CEDCD66";
14
15    // Convert To Binary And Unwraps The Result | Input can be &str or String
16    let bin_string = BinaryString::from_hex(input_hex).unwrap();
17
18    // Prints Out Information
19    println!("Blake2b Hexadecimal: {}", input_hex);
20    println!("Binary String: {}", bin_string);
21}
22
23fn str_func() {
24    // Converts &str to Binary String
25    let bin_string = BinaryString::from("Hello");
26
27    println!("Binary: {}", bin_string)
28}
29
30fn string() {
31    // UTF-8 String of "Hello World" | 11 bytes
32    // Then Convert To Binary From String Using A Variable And Clone (If Possible, avoid using clone for performance)
33    let utf8_string = String::from("Hello World");
34    let bin_string = BinaryString::from(utf8_string.clone());
35
36    // Or, Even Easier And In One Line
37    let bin_string_easy = BinaryString::from(String::from("Hello World"));
38
39    // Asserts Both Strings Are Equal and Asserts Hello World In Binary
40    assert_eq!(bin_string, bin_string_easy);
41    assert_eq!(
42        bin_string.0,
43        "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100"
44    );
45
46    // Prints Out Information
47    println!("UTF-8 String: {}", &utf8_string);
48    println!("Binary String: {}", bin_string);
49}
50
51fn vector() {
52    // A Vector of 4 bytes
53    let input_vector: Vec<u8> = vec![111, 23, 55, 28];
54
55    // Conversion of Vector into Binary String (can also choose to use a slice of the vector to implement copy)
56    let bin_string = BinaryString::from(input_vector);
57
58    // Prints Out Information
59    println!("Vector of [111,23,55,28] u8 bytes");
60    println!("Binary String {}", bin_string);
61}
62
63fn byte() {
64    // Single u8 Byte
65    let byte: u8 = 111u8;
66
67    // `BinaryString` from a Single Byte
68    let bin_string = BinaryString::from(byte);
69
70    // Attempt To Add Spaces
71    let spaces = bin_string.add_spaces().unwrap();
72
73    assert_eq!(bin_string, spaces);
74}