Search code examples
cbinaryfilesfwrite

How to write a binary integer to binary file | c


For example: If I had this integer 10101011 I want to write 10101011 to binary file in 1 byte

Somthing like this,I thought but its not working

FILE *f;
int n=10101011;
f=fopen("file","wb");
Fwrite(&n,1,1,f);

Why you are always does -1 I search and I didnt find something that helped me!!



Solution

  • Seems that you want to convert a binary to decimal:

    #include <stdio.h>
    
    int main(void)
    {
        unsigned char c = 0;
        int x = 10101011;
        int rem, i;
    
        for (i = 0; i < 8; i++) {
            rem = x % 10;
            if (rem == 1) {
                c |= 1U << i;
            }
            x /= 10;
        }
        printf("0x%x\n", c);
        return 0;
    }
    

    Output:

    0xab
    

    Note that you can't use more than 8 digits for x