Search code examples
c++bytebinaryfilesreinterpret-cast

How does the reinterpret_cast work?


I'm wondering how does reinterpret_cast work behind the scenes. I'm learning about it from a book, but i just don't get it. E.g. suppose i have the following part of code:

int a = 255;
char *pChar = reinterpret_cast<char*>(&a);

or

std::string str = "Hello";
char *pChar = reinterpret_cast<char*>(&str);

What will pChar pointed to in both examples, why i can't see anything when i try to print their contents, and of course how does reinterpret_cast work?

Edit: I know reinterpret_cast is pretty dangerous to use, and only want to use it to write bytes directly into a binary file from a block of memory. What i don't understand is that when i have an

int a = 255; (00 00 00 FF in memory)

and i want to treat the variable a as a series of bytes, char* :

char *pChar = reinterpret_cast<char*>(&a);

Will pChar point to the individual bytes of variable a (00 00 00 FF)?

So when i want to write into a binary file what the pChar pointed to:

a_file.write(reinterpret_cast<char*>(&a), sizeof(a));

It writes the individual bytes of variable a, right?


Solution

  • What will pChar pointed to in both examples?

    They will point to the first char of the memory where these variables are reside.

    why i can't see anything when i try to print their contents

    You maybe do it in a wrong way. You cannot print them as a null terminated string (for example, a's internal representation contains 0, which will be treated as a terminating zero).

    You can print them like this:

    for (size_t i=0; i<sizeof(int); i++) {
        printf("%02x ", pChar[i]);
    }
    printf("\n");
    

    This will print the character values of a in hexadecimal. This way, you'll see ff 00 00 00 (assuming that you're on a little endian machine).

    You can do the same with std::string. You'll see the memory representation of std::string.

    (You can print contents as char with "%c". If you redirect stdout to a file, you'll see the internal representation of the variable in the file.

    and of course how does reinterpret_cast work?

    It just reinterprets its parameter, pretending that it has another type. No runtime costs involved (note: this explanation is highly simplified).

    Will pChar point to the individual bytes of variable a (00 00 00 FF)?

    Yes, assuming that char is a byte, and you're on a big endian machine.

    It writes the individual bytes of variable a, right

    Yes, but presumably you can do the same without any reinterpret_cast too, it is not needed here (supposing that a_file.write's first argument is a void *)