Search code examples
cbytefwritefreadunsigned-integer

Write a byte to a file in C


I have a byte declared as unsigned int 0b11010101how can I write this to a binary file as 1 byte? I know fwrite takes type const void *as a buffer but I don't know how to write my byte if it's represented as an unsigned int.


Solution

  • Perhaps like this, you better not write one byte of an int because of endianness. Convert to unsigned char first.

    unsigned int intval = 0b11010101;       // assuming compiler likes it
    unsigned char charval = intval;
    fwrite (&charval, 1, 1, stream);