1

Clarification is needed with reinterpret_cast.

I am building .wav file where various data is inputted as 2 or 4 bytes in hexadecimal bits (if I am correct).

Then, I came across a simple function like this:

void writeToFile(std::ofstream &file, int value, int size)
{
    file.write(reinterpret_cast<char*>(&value), size);
}

As far as I understand what reinterpret_cast does is that it changes the data type in the address a pointer points to!

For example:

int* intPtr{ new int{7} };
char* charPtr{ reinterpret_cast<char*>(intPtr) };

So here we got a new pointer that is supposed to point to char value instead of original int.

If so, then I don't understand validity of the above function void writeToFile(std::ofstream &file, int value, int size), because if I follow my logic, then in this function an int value can't be written to file as the pointer supposedly points to char value, not int!

P.S. Even if a file is opened in std::ios::binary mode, how does it exactly work? How do bits of int become bits of char?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Sakesfar
  • 21
  • 4
  • 2
    Unrelated nitpick: A bit is always binary, never hexadecimal. – jabaa Oct 11 '22 at 13:01
  • 4
    `reinterpret_cast` doesn't change data. It only changes how the compiler interprets the data. The same data causes different behavior depending on the interpretation, e.g. because of function overloading. `std::cout` can print the same data as `97` or `a` depending on the data type. Both values have the same bit pattern on many systems. – jabaa Oct 11 '22 at 13:04
  • 1
    Remember `char` acts as byte in C++. So what is happening is the bytes of the machine representation of the integer value are written out. I'm guessing the argument `size` is `sizeof(int)` or equivalent. It looks like somewhere there's an assumption that the byte ordering on your hardware platform is applicable to the .wav file. – Persixty Oct 11 '22 at 13:14
  • 1
    Perhaps OP does not know that _all types_ in memory or files are "a collection of bytes", and it is up a program to decide whether any collection of bytes should be treated as an `int` or any other type. – Drew Dormann Oct 11 '22 at 13:17
  • 2
    [Dupe1](https://stackoverflow.com/questions/54242711/reinterpret-casted-value-varies-by-compiler), [Dupe2](https://stackoverflow.com/questions/39854610/casting-int-pointer-to-char-pointer), [Dupe3](https://stackoverflow.com/questions/59471703/why-cant-we-static-cast-a-char-pointer-to-an-int-pointer) and [Dupe4](https://stackoverflow.com/questions/6564574/testing-for-endianness-why-does-the-following-code-work). – Jason Oct 11 '22 at 13:27

0 Answers0