Vincent
Vincent

Reputation: 60391

Hexadecimal value of bytes in c++ to a string (equivalent of od -x in linux)?

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 ?

Upvotes: 0

Views: 600

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477140

Here's the standard answer:

template <typename T>
std::string hexify(T const & x)
{
    char const alphabet[] = "0123456789ABCDEF";

    std::string result(2 * sizeof x, 0);
    unsigned char const * const p = reinterpret_cast<unsigned char const *>(&x);

    for (std::size_t i = 0; i != sizeof x; ++i)
    {
        result[2 * i    ] = alphabet[p[i] / 16];
        result[2 * i + 1] = alphabet[p[i] % 16];
    }

    return result;
}

Upvotes: 2

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

You can do something like this:

template<typename T> 
std::string hexOf(const T& x)
{
    std::string rc;
    rc.reserve(2 * sizeof(x));
    for (unsigned char* it(reinterpret_cast<char const*>(&x)), end(it + sizeof(x));
         it != end; ++it) {
        rc.push_back((*it / 16)["0123456789abcdef"]);
        rc.push_back((*it % 16)["0123456789abcdef"]);
    }
    return rc;
}

Upvotes: 0

Related Questions