Question

I have found out this way:

ofstream out("test", ios::out | ios::binary);
UINT16 myint16=16;
out.write((char*)&myint16, sizeof(myint16));

But are there ways to write INT16 binary without declaring a variable?

Was it helpful?

Solution

You can write your own operator<< like that:

std::ofstream& operator<<(std::ofstream& ofs, UINT16 d) {
  ofs.write((char*)&d, sizeof(UINT16));
  return ofs;
}

int main(int, char*[])
{
 ofstream out("test", ios::out | ios::binary);
 out << static_cast<UINT16>(16); // no variable declared
}

also with C++11 you could use user defined literals to make it even shorter:

inline UINT16 operator "" _u(unsigned long long value)
{
    return static_cast<UINT16>(value);
}

and then:

out << 16_u;

OTHER TIPS

But are there ways to write INT16 binary without declaring a variable?

Yes, you can use a c-string literal:

out.write("\0\0", 2);

To output correct INT16 values this way, you'll need to know the endianess of the machine where you're compiling and running your program. E.g. to output decimal 16

out.write("\x01\x00", 2); // 16 in big endian format

out.write("\x00\x01", 2); // 16 in little endian format
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top