I have a bit of a weird problem here!
I am trying to write the color table for a 8 bit windows 3.x bitmap file. I just want the file to be greyscale, so i am trying to write bbb0, ggg0, rrr0 256 times where r=g=b=1..256
//write greyscale color table
for (int i = 255; i >= 0; i--) {
writeS = (unsigned short)i;
outfile.write ((char*)&writeS,sizeof(char)); // b
outfile.write ((char*)&writeS,sizeof(char)); // g
outfile.write ((char*)&writeS,sizeof(char)); // r
writeS = 0;
outfile.write ((char*)&writeS,sizeof(char)); // 0
}
When I look at the output i am getting with a hex editor, everything looks fine until I get to the number 10, which is written like so:
…0C 0C 0C 00 0B 0B 0B 00 0D 0A 0D 0A 0D 0A 00 09 09 09 00 08 08 08 00…
isntead of:
…0C 0C 0C 00 0B 0B 0B 00 0A 0A 0A 00 09 09 09 00 08 08 08 00…
So that is wierd that it is only doing it on this one number, but what is even wierder is that when I change the code to skip the number 10 and write 9 instead, it works.
//write greyscale color table
for (int i = 255; i >= 0; i--) {
writeS = (unsigned short)i;
if (writeS == 10) writeS = 9;
outfile.write ((char*)&writeS,sizeof(char)); // b
outfile.write ((char*)&writeS,sizeof(char)); // g
outfile.write ((char*)&writeS,sizeof(char)); // r
writeS = 0;
outfile.write ((char*)&writeS,sizeof(char)); // 0
}
gives:
…0C 0C 0C 00 0B 0B 0B 00 09 09 09 00 09 09 09 00 08 08 08 00…
Is there something weird going on there with notation? Any obvious errors that I have missed? Has anyone ran into something like this before?
Thanks!
The “number 10” in ASCII is the line feed character,
\n. In C++, this is the newline character.You have apparently opened the file as a text stream. Because newlines are represented differently on different platforms, text streams perform newline translation: when reading they translate the platform-specific newline representation into
\nand when writing they translate the\ncharacter into the platform-specific newline representation.On Windows, line breaks are represented by
\r\n. When you write a\nto the text stream, it gets written as\r\n.To write raw binary data, you need to open the stream as a binary stream. This is done by passing the
ios_base::binaryflag to the constructor of the stream.