xref: /openbmc/bmcweb/redfish-core/include/utils/hex_utils.hpp (revision 0ddb8edfb150ddf93b069e655ce3624d1e2fec54)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 
5 #include <array>
6 #include <cstddef>
7 #include <cstdint>
8 #include <format>
9 #include <span>
10 #include <string>
11 #include <vector>
12 
bytesToHexString(const std::span<const uint8_t> & bytes)13 inline std::string bytesToHexString(const std::span<const uint8_t>& bytes)
14 {
15     std::string rc;
16     rc.reserve(bytes.size() * 2);
17     for (uint8_t byte : bytes)
18     {
19         rc += std::format("{:02X}", byte);
20     }
21     return rc;
22 }
23 
24 // Returns nibble.
hexCharToNibble(char ch)25 inline uint8_t hexCharToNibble(char ch)
26 {
27     uint8_t rc = 16;
28     if (ch >= '0' && ch <= '9')
29     {
30         rc = static_cast<uint8_t>(ch) - '0';
31     }
32     else if (ch >= 'A' && ch <= 'F')
33     {
34         rc = static_cast<uint8_t>(ch - 'A') + 10U;
35     }
36     else if (ch >= 'a' && ch <= 'f')
37     {
38         rc = static_cast<uint8_t>(ch - 'a') + 10U;
39     }
40 
41     return rc;
42 }
43 
44 // Returns empty vector in case of malformed hex-string.
hexStringToBytes(const std::string & str)45 inline std::vector<uint8_t> hexStringToBytes(const std::string& str)
46 {
47     std::vector<uint8_t> rc(str.size() / 2, 0);
48     for (size_t i = 0; i < str.length(); i += 2)
49     {
50         uint8_t hi = hexCharToNibble(str[i]);
51         if (i == str.length() - 1)
52         {
53             return {};
54         }
55         uint8_t lo = hexCharToNibble(str[i + 1]);
56         if (lo == 16 || hi == 16)
57         {
58             return {};
59         }
60 
61         rc[i / 2] = static_cast<uint8_t>(hi << 4) | lo;
62     }
63     return rc;
64 }
65