25 #ifndef GOBY_UTIL_BINARY_H
26 #define GOBY_UTIL_BINARY_H
34 #include <boost/dynamic_bitset.hpp>
47 inline void hex_decode(
const std::string& in, std::string* out)
49 static const short char0_9_to_number = 48;
50 static const short charA_F_to_number = 55;
51 static const short chara_f_to_number = 87;
53 int in_size = in.size();
54 int out_size = in_size >> 1;
58 out->assign(out_size,
'\0');
59 for (
int i = (in_size & 1) ? -1 : 0, n = in_size; i < n; i += 2)
61 int out_i = (in_size & 1) ? (i + 1) / 2 : i / 2;
65 if (in[i] >=
'0' && in[i] <=
'9')
66 (*out)[out_i] |= ((in[i] - char0_9_to_number) & 0x0f) << 4;
67 else if (in[i] >=
'A' && in[i] <=
'F')
68 (*out)[out_i] |= ((in[i] - charA_F_to_number) & 0x0f) << 4;
69 else if (in[i] >=
'a' && in[i] <=
'f')
70 (*out)[out_i] |= ((in[i] - chara_f_to_number) & 0x0f) << 4;
73 if (in[i + 1] >=
'0' && in[i + 1] <=
'9')
74 (*out)[out_i] |= (in[i + 1] - char0_9_to_number) & 0x0f;
75 else if (in[i + 1] >=
'A' && in[i + 1] <=
'F')
76 (*out)[out_i] |= (in[i + 1] - charA_F_to_number) & 0x0f;
77 else if (in[i + 1] >=
'a' && in[i + 1] <=
'f')
78 (*out)[out_i] |= (in[i + 1] - chara_f_to_number) & 0x0f;
94 inline void hex_encode(
const std::string& in, std::string* out,
bool upper_case =
false)
96 static const short char0_9_to_number = 48;
97 static const short charA_F_to_number = 55;
98 static const short chara_f_to_number = 87;
100 int in_size = in.size();
101 int out_size = in_size << 1;
103 out->resize(out_size);
104 for (
int i = 0, n = in_size; i < n; ++i)
106 short msn = (in[i] >> 4) & 0x0f;
107 short lsn = in[i] & 0x0f;
109 if (msn >= 0 && msn <= 9)
110 (*out)[2 * i] = msn + char0_9_to_number;
111 else if (msn >= 10 && msn <= 15)
112 (*out)[2 * i] = msn + (upper_case ? charA_F_to_number : chara_f_to_number);
114 if (lsn >= 0 && lsn <= 9)
115 (*out)[2 * i + 1] = lsn + char0_9_to_number;
116 else if (lsn >= 10 && lsn <= 15)
117 (*out)[2 * i + 1] = lsn + (upper_case ? charA_F_to_number : chara_f_to_number);
133 std::stringstream ss;
145 template <
typename T>
bool number2hex_string(std::string& s,
const T& t,
unsigned int width = 2)
147 std::stringstream ss;
148 ss << std::hex << std::setw(width) << std::setfill('0') << static_cast<unsigned int>(t);