4

I have a std::string representing a 64-bit memory address in little-endian, hexadecimal form. How to convert this to a uint64_t representation?

4

1 回答 1

5
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
#include <cstdint>

int main()
{
    std::string s("0x12345");
    std::stringstream strm(s);
    std::uint64_t n;
    strm >> std::hex >> n;
    std::cout << std::hex << n << std::endl;
    return 0;
}

This prints 12345, as expected.

Edit: If you want to convert from little-endian to big-endian, that's possible too:

#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstdint>

int main()
{
    std::string s("0x12345");
    std::stringstream strm(s);

    union {
        std::uint64_t n;
        std::uint8_t a[8];
    } u;

    strm >> std::hex >> u.n;
    std::reverse(u.a, u.a + 8);

    std::cout << std::hex << std::setfill('0') << std::setw(16) << u.n << std::endl;
    return 0;
}
于 2013-07-15T19:11:27.063 回答