In answer to your original question about writing 2-bytes out in binary to a file in C++, you have a basic 2-step process. (1) convert your string representation of the number to a numeric value using stoi
with base 16
. This provides a numeric values you can store in an unsigned short
. (2) write that value out to your file with f.write
, not frwite
where f
is your open stream reference.
If you want to format the output in hex for cout
, then you must set the flags for cout
to output numeric values in hex-format (though not directly part of your question, it ties in the stream I/O formatting if desired.)
So essentially you have your string and convert it to a number, e.g.
std::string str = "e101";
unsigned short u = stoi(str, 0, 16);
Now u
holds a numeric value converted from the text in str
using base-16 that you can simply write to your file as a 2-byte value, e.g.
std::string filename = "out.bin"; /* output filename */
...
std::ofstream f (filename, f.trunc | f.binary); /* open out in binary */
if (!f.write(reinterpret_cast<char*>(&u), sizeof u)) { /* write 2 bytes */
std::cerr << "error: write of short to file failed.\n";
return 1;
}
Putting it altogether, you could do something short that outputs the hex value being written with cout
as well as writing it to the file "out.bin"
, e.g.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
int main (void) {
std::string filename = "out.bin"; /* output filename */
std::string str = "e101";
unsigned short u = stoi(str, 0, 16);
/* output converted value to terminal in hex */
std::cout.setf(std::ios::hex, std::ios::basefield); /* set hex output */
std::cout << "writing value to file: " << u << '\n'; /* for cout */
/* output converted value to file */
std::ofstream f (filename, f.trunc | f.binary); /* open out in binary */
if (!f.write(reinterpret_cast<char*>(&u), sizeof u)) { /* write 2 bytes */
std::cerr << "error: write of short to file failed.\n";
return 1;
}
}
Example Use/Output
$ ./bin/stoi_short
writing value to file: e101
Resulting Output File
Confirm by dumping the contents of the file with a hexdump program, e.g.
$ hexdump out.bin
0000000 e101
0000002
Look things over and let me know if you have further questions.