Writing bits to a file in C

前端 未结 5 361
时光说笑
时光说笑 2021-02-03 22:14

I have this string: \"101\" I want to write it to a file, in C, not as text: \"101\" and so 8 bits x char. but directly use the string as bits: the bit \"1\", the bit \"0\" and

5条回答
  •  臣服心动
    2021-02-03 22:55

    All filesystems¹ deal with files in terms of bytes (and allocate storage space with a much larger granularity, 512 bytes at a time minimum). There's no way you are going to get a file that is 3 bits long.

    The best you can do is use up one whole byte but ignore 5 of its bits. To do that (assuming that the number is always going to fit into a byte), convert the input string to an integral type:

    long l = strtol(c, 0, 2);
    

    Then get its least significant byte:

    unsigned char b = l & 0xffl;
    

    And write it to the file:

    fwrite(&b, 1, 1, binFile);
    

    ¹ Well, maybe not all. There might be some researchers somewhere that experiment with bit-sized filesystems. I wouldn't know.

提交回复
热议问题