llvm.org GIT mirror llvm / 3995e3e
[StringExtras] Add a fromHex to complement toHex. We already have a function toHex that will convert a string like "\xFF\xFF" to the string "FFFF", but we do not have one that goes the other way - i.e. to convert a textual string representing a sequence of hexadecimal characters into the corresponding actual bytes. This patch adds such a function. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@301356 91177308-0d34-0410-b5e6-96231b3b80d8 Zachary Turner 3 years ago
2 changed file(s) with 46 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
7171 const unsigned char c = Input[i];
7272 Output.push_back(LUT[c >> 4]);
7373 Output.push_back(LUT[c & 15]);
74 }
75 return Output;
76 }
77
78 static inline uint8_t hexFromNibbles(char MSB, char LSB) {
79 unsigned U1 = hexDigitValue(MSB);
80 unsigned U2 = hexDigitValue(LSB);
81 assert(U1 != -1U && U2 != -1U);
82
83 return static_cast((U1 << 4) | U2);
84 }
85
86 /// Convert hexadecimal string \p Input to its binary representation.
87 /// The return string is half the size of \p Input.
88 static inline std::string fromHex(StringRef Input) {
89 if (Input.empty())
90 return std::string();
91
92 std::string Output;
93 Output.reserve((Input.size() + 1) / 2);
94 if (Input.size() % 2 == 1) {
95 Output.push_back(hexFromNibbles('0', Input.front()));
96 Input = Input.drop_front();
97 }
98
99 assert(Input.size() % 2 == 0);
100 while (!Input.empty()) {
101 uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
102 Output.push_back(Hex);
103 Input = Input.drop_front(2);
74104 }
75105 return Output;
76106 }
4949
5050 EXPECT_EQ("foo/bar/baz/x", join_items('/', Foo, Bar, Baz, X));
5151 }
52
53 TEST(StringExtrasTest, ToAndFromHex) {
54 std::vector OddBytes = {0x5, 0xBD, 0x0D, 0x3E, 0xCD};
55 std::string OddStr = "05BD0D3ECD";
56 StringRef OddData(reinterpret_cast(OddBytes.data()),
57 OddBytes.size());
58 EXPECT_EQ(OddStr, toHex(OddData));
59 EXPECT_EQ(OddData, fromHex(StringRef(OddStr).drop_front()));
60
61 std::vector EvenBytes = {0xA5, 0xBD, 0x0D, 0x3E, 0xCD};
62 std::string EvenStr = "A5BD0D3ECD";
63 StringRef EvenData(reinterpret_cast(EvenBytes.data()),
64 EvenBytes.size());
65 EXPECT_EQ(EvenStr, toHex(EvenData));
66 EXPECT_EQ(EvenData, fromHex(EvenStr));
67 }