DebugServer2
Loading...
Searching...
No Matches
HexValues.h
1//
2// Copyright (c) 2014-present, Facebook, Inc.
3// All rights reserved.
4//
5// This source code is licensed under the University of Illinois/NCSA Open
6// Source License found in the LICENSE file in the root directory of this
7// source tree. An additional grant of patent rights can be found in the
8// PATENTS file in the same directory.
9//
10
11#pragma once
12
13#include "DebugServer2/Utils/CompilerSupport.h"
14#include "DebugServer2/Utils/Log.h"
15#include "DebugServer2/Types.h"
16
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <string>
21
22namespace ds2 {
23
24static inline char NibbleToHex(uint8_t byte) {
25 return "0123456789abcdef"[byte & 0x0f];
26}
27
28static inline uint8_t HexToNibble(char ch) {
29 if (ch >= '0' && ch <= '9')
30 return ch - '0';
31 else if (ch >= 'a' && ch <= 'f')
32 return ch - 'a' + 10;
33 else if (ch >= 'A' && ch <= 'F')
34 return ch - 'A' + 10;
35 DS2_UNREACHABLE();
36}
37
38static inline uint8_t HexToByte(char const *chars) {
39 return (HexToNibble(chars[0]) << 4) | HexToNibble(chars[1]);
40}
41
42template <typename T> static inline std::string ToHex(T const &vec) {
43 std::string result;
44 for (char n : vec) {
45 result += NibbleToHex(n >> 4);
46 result += NibbleToHex(n & 0x0f);
47 }
48 return result;
49}
50
51static inline ByteVector HexToByteVector(std::string const &str) {
52 ByteVector result;
53 DS2ASSERT(str.size() % 2 == 0);
54 for (size_t n = 0; n < str.size(); n += 2) {
55 result.emplace_back(HexToByte(&str[n]));
56 }
57 return result;
58}
59
60static inline std::string HexToString(std::string const &str) {
61 std::string result;
62 DS2ASSERT(str.size() % 2 == 0);
63 for (size_t n = 0; n < str.size(); n += 2) {
64 result += static_cast<char>(HexToByte(&str[n]));
65 }
66 return result;
67}
68} // namespace ds2