dharitri_sc/formatter/
hex_util.rs1use alloc::string::String;
2
3fn half_byte_to_hex_digit(num: u8) -> u8 {
4 if num < 10 {
5 b'0' + num
6 } else {
7 b'a' + num - 0xau8
8 }
9}
10
11pub fn byte_to_hex_digits(byte: u8) -> [u8; 2] {
12 let digit1 = half_byte_to_hex_digit(byte >> 4);
13 let digit2 = half_byte_to_hex_digit(byte & 0x0f);
14 [digit1, digit2]
15}
16
17pub fn encode_bytes_as_hex(input: &[u8]) -> String {
18 let mut result = String::new();
19 for &byte in input {
20 let bytes = byte_to_hex_digits(byte);
21 result.push(bytes[0] as char);
22 result.push(bytes[1] as char);
23 }
24 result
25}
26
27fn hex_digit_to_half_byte(digit: u8) -> Option<u8> {
28 if digit.is_ascii_digit() {
29 return Some(digit - b'0');
30 }
31 if (b'a'..=b'f').contains(&digit) {
32 return Some(digit - b'a' + 0xau8);
33 }
34 None
35}
36
37pub fn hex_digits_to_byte(digit1: u8, digit2: u8) -> Option<u8> {
38 let mut result = match hex_digit_to_half_byte(digit1) {
39 None => {
40 return None;
41 },
42 Some(num) => num << 4,
43 };
44 match hex_digit_to_half_byte(digit2) {
45 None => {
46 return None;
47 },
48 Some(num) => {
49 result |= num;
50 },
51 };
52 Some(result)
53}
54
55pub fn byte_to_binary_digits(mut num: u8) -> [u8; 8] {
56 let mut result = [b'0'; 8];
57 let mut i = 7i32;
58 while i >= 0 {
59 result[i as usize] += num % 2;
60 num /= 2;
61 i -= 1;
62 }
63 result
64}