0

I am casting an unsigned int(64 bit) for some use case inside the program(C++). I tried with an example and wondering why the answer is in reverse of what it actually should be?

Example:

#include <iostream>

using namespace std;

std::string string_to_hex(const std::string& input)
{
    static const char hex_digits[] = "0123456789ABCDEF";

    std::string output;
    output.reserve(input.length() * 2);
    for (unsigned char c : input)
    {
        output.push_back(hex_digits[c >> 4]);
        output.push_back(hex_digits[c & 15]);
    }
    return output;
}

int main()
{
    uint64_t foo = 258; // (00000001)(00000010) => (01)(02)

    std::string out = "";
    out.append(reinterpret_cast<const char*>(&foo), sizeof(foo));
    
    std::cout << "out: " << string_to_hex(out) << std::endl;
    
    return 0;
}

I intentionally used that number(258) to see the result something like: (00)(00)(00)(00)(00)(00)(01)(02) after converting to hex. But it is giving me the result:

out: 0201000000000000

I asked one related question earlier: Why same values inside string even after swapping the underlying integer?, but I'm not sure they have the same underlying cause.

It maybe a trivial mistake from my side, but I thought it is worth posting and sort it out incase I'm missing some concept.

DonBaka
  • 325
  • 2
  • 14
  • 7
    It looks like you are using a **little-endian** machine. – MikeCAT Mar 29 '22 at 11:24
  • If you want a string, why not use e.g. `std::ostringstream` and the normal streaming manipulators to get it? As in `std::string output = (std::ostringstream() << std::hex << std::setw(16) << std::setfill('0') << foo).str();` – Some programmer dude Mar 29 '22 at 11:30
  • And if you have C++20 and [`std::format`](https://en.cppreference.com/w/cpp/utility/format/format) then `std::format("{:016x}", foo)` – Some programmer dude Mar 29 '22 at 11:35
  • 1
    I recommend https://en.wikipedia.org/wiki/Endianness -- bytes of integral types are not always stored in memory they way you think. Most modern hardware uses the "little endian" format, and many network protocols use "big endian" instead. – chi Mar 29 '22 at 11:57
  • @Someprogrammerdude thanks for the response, so actually using the cast for byte wise handling of data for some program purpose – DonBaka Mar 29 '22 at 12:31

0 Answers0