First of all, some basics.
Writing data "in binary form" doesn't mean anything special. The program just takes whatever it has in RAM and dumps it to a file. This means that something like this:
uint8_t x = 10;
fwrite(&x, sizeof(uint8_t), 1, some_file);
Will result in the binary value of 10
directly written into the opened some_file
. Since the value 10
is stored in a uint_8
and sizeof(uint_8)
is 1 (one byte), that call will end up writing exactly one byte. The binary representation (as one byte) of 10
is 00001010
.
If, after writing a binary file, you try to open it using a text editor, or you try to print it to the terminal using something like cat
, it will be interpreted as text based on the encoding that is configured in the text editor or terminal. This will most probably result in random and strange letters, because that binary data is just not meant to be representing some text, but just integer values of one byte. This can only be known by who created the file. The binary data itself can have infinite interpretations.
With that said, what you see there:
ÿ\0\0ÿ\0\0ÿ\0\0ÿ\0\0ÿ
Is exactly what I described. To be able to see the real values you should pass that output to an hex viewer, like the hd
command for example:
$ hd your_file
00000000 c3 bf 00 00 c3 bf 00 00 c3 bf 00 00 c3 bf 00 00 |................|
00000010 c3 bf |..|
00000012
If that text was displayed using UTF-8 (most probably), the bytes that were written are the ones displayed above, which, converted from hexadecimal to decimal, are:
195 191 0 0 195 191 0 0 195 191 0 0 195 191 0 0 195 191
Now, talking about the actual code you posted:
What you are doing is right, assuming that your 2D array is Nx3. To write binary data to a file, fwrite()
is the right function.
So, this:
fwrite(color_array[i], sizeof(uint8_t), 3, output);
Is writing the i-th row of the 2D array, which consists of 3 uint8_t
values, to the file, in binary form.
As an example, consider the following:
uint8_t color_array[2][3] = {{1, 2, 3}, {10, 11, 12}};
fwrite(color_array[0], sizeof(uint8_t), 3, output);
fwrite(color_array[1], sizeof(uint8_t), 3, output);
This will make you end up with a file that looks like this:
$ hd your_file
00000000 01 02 03 0a 0b 0c |......|
00000006