I'm trying to format a binary array: char* memblock to a hex string.
When I use the following:
fprintf(out, "0x%02x,", memblock[0]);
I get the following output:
0x7f,
When I try to use boost::format on an ofstream like so:
std::ofstream outFile (path, std::ios::out); //also tried with binary
outFile << (boost::format("0x%02x")%memblock[0]);
I get a weird output like this (seen in Vi): 0x0^?.
What gives?
Given that the character for
0x7fis CTRL-?, it looks like it's outputting thememblock[0]as a character rather than a hex value, despite your format string.This actually makes sense based on what I've read in the documentation.
Boost::formatis a type-safe library where the format specifiers dictate how a variable will be output, but limited by the actual type of said variable, which takes precedence.The documentation states (my bold):
And presumably, having the field flag set to hex doesn't make a lot of sense when you're printing a
char, so it's ignored. Additionally from that documentation (though paraphrased a little):This is also verified more specifically by the text from this link:
The Boost documentation linked to above also explains that the zero-padding
0modifier works on all types, not just integral ones, which is why you're getting the second0in0x0^?(the^?is a single character).In many ways, this is similar to the problem of trying to output a
const char *in C++ so that you see a pointer. The following code:will produce something like:
because the standard libraries know that C-style strings are a special case but, if you tell them it's a void pointer, they'll give you a pointer as output.
A solution in your specific case may be just to cast your
charto anintor some other type that intelligently handles the%xformat specifier: