Writing bits to a file in C

前端 未结 5 454
时光说笑
时光说笑 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 23:13

    What you can do is write it as bits (3) and fill it up to a byte with 0's. However, you also need to start (or end) with the number of bits (or bits from the last byte) that are really used.

    E.g. (using first byte as length):

    00000011   -> 3, meaning from the last (and only byte in this case, 
                  only the first 3 bits are used)
    10100000   -> 101 is the string, other 5 bits are 0, just use for padding
    

    In this case the overhead of the first (length) byte is 50%, the longer the string, the less the overhead percentage of course.

提交回复
热议问题