Is there any command in stl that converts ascii data to the integer form of its hex representation? such as: “abc” -> 0x616263.
i have the most basic way i can think of:
uint64_t tointeger(std::string){
std::string str = "abc";
uint64_t value = 0; // allow max of 8 chars
for(int x = 0; x < str.size(); x++)
value = (value << 8) + str[x];
return value;
}
as stated above: tointeger("abc"); returns the value 0x616263
but this is too slow. and because i have to use this function hundreds of thousands of times, it has slowed down my program significantly. there are 4 or 5 functions that rely on this one, and each of those are called thousands of times, in addition to this function being called thousands of times
what is a faster way to do this?
You want to pack ASCII characters from a string into a 64-bit integer.
Since std::string is not an intrinsic type, for safety, copy the data into a buffer:
The copying is more safe as far as alignments go. To be faster, but more dangerous, just avoid the copy:
The
std::string::c_strmethod returns a pointer to a c-style string representation of the text, but the text is not guaranteed to last forever, thus the need to copy. Also, the pointer is only guaranteed to be on a character alignment. Thus if it happens to reside at address 0x1003, the processor may generate an alighnment fault (or slow down because it has to fetch at an un-aligned boundary).Edit 1:
This method does not take into consideration Endianness. The method uses the Endianness of the platform. Changing Endianness will slow the performance.