assuming i have a string containing hexadecimal digits where every 2 hex digits represents a character in the ASCII set and i need to convert the string containing hex digits back to its character equivalent
i found what i was looking for in this code:-
#include <algorithm>
#include <stdexcept>
std::string hex_to_string(const std::string& input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
if (len & 1) throw std::invalid_argument("odd length");
std::string output;
output.reserve(len / 2);
for (size_t i = 0; i < len; i += 2)
{
char a = input[i];
const char* p = std::lower_bound(lut, lut + 16, a);
if (*p != a) throw std::invalid_argument("not a hex digit");
char b = input[i + 1];
const char* q = std::lower_bound(lut, lut + 16, b);
if (*q != b) throw std::invalid_argument("not a hex digit");
output.push_back(((p - lut) << 4) | (q - lut));
}
return output;
}
i am rather new to C++ and i could understand till the part output.push_back(((p – lut) << 4) | (q – lut));
suppose the string contains a hex value of 72 (which represents the char ‘r’ in ACSII) and just before the push_back operation for the output string, the value of p and lut would be:-
p = “789ABCDEF”
lut = “0123456789ABCDEF”
but, (p – lut) in this function is yielding 7 as a result. i don’t quite understand how this happens.??
That’s pointer arithmetic.
The value of
pis not"7890ABCDEF". Rather that’s the content stored at the address held inp. Sincepis a pointer, it’s value is an address.lutpoints to element 0,ppoints to element 7 in the same array. Thereforep - lutis 7.For any
n,p + nis the same as&p[n], that is, the address of then-th element. Here that fact is used in reverse.