'Why casting integer is giving reverse answer? [duplicate]

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source