My goal is to write the more concise/effective function to convert a value to an hexadecimal string AS it is stored in memory (so the printed value will depends on the system endianness for example) :
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <string>
template<typename T>
std::string hexOf(const T& x)
{
return std::string(reinterpret_cast<const char*>(&x), sizeof(x));
}
int main()
{
std::cout<<hexOf(9283)<<std::endl;
return 0;
}
The current implementation does not work because the string contains the characters, but not the actual hex representation of the characters.
The final result I expect is hexOf(0xA0B70708) return the string 0807b7a0 on a little endian-system.
How to do that in a concise/effective way ?
Here’s the standard answer: