Writing bits to a file in C

前端 未结 5 434
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2021-02-03 22:57

    2 notes on your approach:

    1. [Modern] Computers can't handle less than 1 byte in memory, so you won't be able to write single bits to disk.

      Also, filesystems usually allocate space in chunks (512 bytes, 1Kb, ...) where the file fits. So, if you have a 500 bytes file, you are actually loosing 512 bytes of disk space.

    2. atoi() doesn't convert from string to binary numbers, but to integer. You are actually writing 0b1100101, which is 0d101. You should do the conversion first. Something like:

      char b = 0;
      for (int i=0; c[i]!=NULL; i++) 
      {
          b = ((b<<1) | atoi(c[i]));
      }
      

提交回复
热议问题