Skip to main content

rustdom_x/
byte_string.rs

1//TODO Rename to hex2_u8_array
2pub fn string_to_u8_array(hex: &str) -> Vec<u8> {
3    let mut bytes = Vec::new();
4    for i in 0..(hex.len() / 2) {
5        let res = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16);
6        match res {
7            Ok(v) => bytes.push(v),
8            Err(e) => {
9                error!("Problem with hex: {}", e);
10                return bytes;
11            }
12        };
13    }
14    bytes
15}
16
17/// Converts the first 8 hex chars of the slice to a u32
18/// number. The hex string is interpreted as litte-endian
19/// (last two chars are most signifiant)
20pub fn hex2_u32_le(hex: &str) -> u32 {
21    let mut result: u32 = 0;
22    for k in (0..8).step_by(2) {
23        let p = u32::from_str_radix(&hex[(8 - k - 2)..(8 - k)], 16).unwrap();
24        result <<= 8;
25        result |= p;
26    }
27    result
28}
29
30//TODO Write a test
31pub fn hex2_u64_le(hex: &str) -> u64 {
32    let mut result: u64 = 0;
33    for k in (0..hex.len()).step_by(2) {
34        let p = u64::from_str_radix(&hex[(hex.len() - k - 2)..(hex.len() - k)], 16).unwrap();
35        result <<= 8;
36        result |= p;
37    }
38    result
39}
40
41pub fn hex2_u64_be(hex: &str) -> u64 {
42    u64::from_str_radix(hex, 16).unwrap()
43}
44
45pub fn u8_array_to_string(a: &[u8]) -> String {
46    let mut str = String::new();
47    for a_i in a {
48        str.push_str(&format!("{:02x}", a_i));
49    }
50    str
51}
52
53pub fn u128_to_string(u: u128) -> String {
54    return format!("{:016x}", u);
55}