Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading