23 #ifndef BINARY20100713H 24 #define BINARY20100713H 32 #include <boost/dynamic_bitset.hpp> 45 inline void hex_decode(
const std::string& in, std::string* out)
47 static const short char0_9_to_number = 48;
48 static const short charA_F_to_number = 55;
49 static const short chara_f_to_number = 87;
51 int in_size = in.size();
52 int out_size = in_size >> 1;
56 out->assign(out_size,
'\0');
57 for (
int i = (in_size & 1) ? -1 : 0, n = in_size; i < n; i += 2)
59 int out_i = (in_size & 1) ? (i + 1) / 2 : i / 2;
63 if (in[i] >=
'0' && in[i] <=
'9')
64 (*out)[out_i] |= ((in[i] - char0_9_to_number) & 0x0f) << 4;
65 else if (in[i] >=
'A' && in[i] <=
'F')
66 (*out)[out_i] |= ((in[i] - charA_F_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;
71 if (in[i + 1] >=
'0' && in[i + 1] <=
'9')
72 (*out)[out_i] |= (in[i + 1] - char0_9_to_number) & 0x0f;
73 else if (in[i + 1] >=
'A' && in[i + 1] <=
'F')
74 (*out)[out_i] |= (in[i + 1] - charA_F_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;
80 inline std::string hex_decode(
const std::string& in)
92 inline void hex_encode(
const std::string& in, std::string* out,
bool upper_case =
false)
94 static const short char0_9_to_number = 48;
95 static const short charA_F_to_number = 55;
96 static const short chara_f_to_number = 87;
98 int in_size = in.size();
99 int out_size = in_size << 1;
101 out->resize(out_size);
102 for (
int i = 0, n = in_size; i < n; ++i)
104 short msn = (in[i] >> 4) & 0x0f;
105 short lsn = in[i] & 0x0f;
107 if (msn >= 0 && msn <= 9)
108 (*out)[2 * i] = msn + char0_9_to_number;
109 else if (msn >= 10 && msn <= 15)
110 (*out)[2 * i] = msn + (upper_case ? charA_F_to_number : chara_f_to_number);
112 if (lsn >= 0 && lsn <= 9)
113 (*out)[2 * i + 1] = lsn + char0_9_to_number;
114 else if (lsn >= 10 && lsn <= 15)
115 (*out)[2 * i + 1] = lsn + (upper_case ? charA_F_to_number : chara_f_to_number);
119 inline std::string hex_encode(
const std::string& in)
122 hex_encode(in, &out);
131 std::stringstream ss;
143 template <
typename T>
bool number2hex_string(std::string& s,
const T& t,
unsigned int width = 2)
145 std::stringstream ss;
146 ss << std::hex << std::setw(width) << std::setfill('0') << static_cast<unsigned int>(t);
156 template <
typename T> std::string
number2hex_string(
const T& t,
unsigned int width = 2)
bool number2hex_string(std::string &s, const T &t, unsigned int width=2)
converts a decimal number of type T into a hex string
bool hex_string2number(const std::string &s, T &t)
converts a hex string ("8AAA") into a dynamic_bitset
The global namespace for the Goby project.