1

I have a binary file of 5 bit numbers in a row that I need to read into an array of unsigned integers where each array value is one 5 bit binary number. I know you can use fread when the values are 1 byte in size, but here the numbers are too small, how should I go about this?

I have just tried using fread but this returns incorrect 8 bit values with a bunch of empty entries at the end of the array.

Timbin
  • 11
  • 1
  • 2
    If bytes are 8 bits, then find a common multiple of both 5 and 8. Read that many bytes, and extract the bits from those bytes. – Some programmer dude Mar 19 '23 at 16:59
  • I have done this by writing a function `freadbits(FILE *fp, int nbits)`. The function keeps some state: some leftover bits, and a count of how many of them there are. So the first call to `freadbits(fp, 5)` would call `getc` to actually read 8 bits, stash 3 of them away for next time, and return 5 to its caller. The second call to `freadbits(fp, 5)` would call `getc` to read 8 more bits, stash 6 of them away for next time, and combine 2 of them with the 3 stashed from last time, to return to the caller. Etc. – Steve Summit Mar 19 '23 at 17:16
  • See also: https://stackoverflow.com/questions/11513466/how-to-write-a-bitstream – Kartheek Tammana Mar 20 '23 at 07:22

1 Answers1

1

You have 5 bit numbers so you can read 5 bytes (8 of your numbers) and then you can extract the numbers by doing bitwise and with 0000....11111 and so on. This has the complexity of merging the 5 bytes that you read. You could also and the first byte 00011111 which will give you the first 5 bit number. Then you and it with 11100000 which will give you the last 3 bits of the second number. Then and the second byte with 00000011 to get the first 2 bits of the 2nd number and so on.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39