Search code examples
cbinaryasciifwrite

Why does the ASCII codes of number characters get written to the file?


I'm writing a binary file with the following code

char x[] = "02 00 27 FF FF 92 20";
FILE *ptr_x;
ptr_x=fopen("xx","wb");
fwrite(x, 1, 1, ptr_x);

The problem is that if i open the file it is written like this:

"30 32 20 30 30 20 32 37 20 46 46 20 46 46 20 39 32 20 32 30"

Which is the ASCII representation of the text above. What i would like to have is a file with exactly those values written in and not the ASCI representation.

Regards,

Solution:

uint8_t x[68] = {0x05,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
                0x00,0x00,0x00,0x18,0xDA,0x18,0xF1,0x18,
                0xDA,0xF1,0x18,0xF1,0x18,0x00,0x05,0x02,
                0x01,0x14,0x00,0x01,0x00,0x0B,0x00,0x33,
                0x01,0x01,0x04,0x02,0x00,0x27,0xFF,0xFF,
                0x92,0x20,0x00,0x00,0x00,0x23,0xFE,0x00,
                0x04,0x02,0x00,0x27,0xFF,0xFF,0x04,0x02,
                0x00,0x23,0xFE,0x00,0x00,0x00,0x00,0x00,
                0x00,0x00,0x92,0x20};

FILE *ptr_x;
ptr_x=fopen("xx","wb");
fwrite(x, 68, 1, ptr_x);

Solution

  • Try using an array like this: unsigned char x[] = {0x02, 0x00, 0x27, 0xFF, 0xFF, 0x92, 0x20}; or, even better, use uint8_t instead of unsigned char.