Home > OS >  Why same values inside string even after swapping the underlying integer?
Why same values inside string even after swapping the underlying integer?

Time:03-22

I have a 64 bit unsigned integer and for some reason I have to store it inside a string. What I am wondering is that the value inside the string is same even after using the swapped integer?

For example:

#include <iostream>
#include <byteswap.h>

using namespace std;

int main()
{
    uint64_t foo = 98;

    uint64_t foo_reversed = bswap_64(foo);
    
    std::string out = "";
    out.append(reinterpret_cast<const char*>(&foo), sizeof(foo));

    std::string out_reversed = "";
    out_reversed.append(reinterpret_cast<const char*>(&foo_reversed), sizeof(foo_reversed));
    
    std::cout << "out: " << out << std::endl;
    std::cout << "out_reversed: " << out_reversed << std::endl;

    return 0;
}

The string out and out_reversed have the exact same value, but I expect it to be different as the underlying integer foo and foo_reversed are swapped value of each other.

What am I missing here? Pardon me if it is a trivial mistake, but putting it out here on the chance that I'm missing some concept.

The output I see:

out: b
out_reversed: b

I was not expecting the above value for out_reversed

CodePudding user response:

You can see the same thing with arrays of char:

int main()
{
    char foo[8] = { 98, 0, 0, 0, 0, 0, 0, 0 };
    char foo_reversed[8] = { 0, 0, 0, 0, 0, 0, 0, 98 };
    
    std::string out(foo, 8);
    std::string out_reversed(foo_reversed, 8);

    std::cout << "out: " << out << std::endl;
    std::cout << "out_reversed: " << out_reversed << std::endl;

    return 0;
}

The chars with value 0 aren't printable, so the terminal doesn't display them

Here's an alternative printing.

  • Related