Reading a binary file bit by bit

Ryan picture Ryan · Jul 27, 2012 · Viewed 30.9k times · Source

I know the function below:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

It only reads byte by byte, my goal is to be able to read 12 bits at a time and then take them into an array. Any help or pointers would be greatly appreciated!

Answer

Carlos Vergara picture Carlos Vergara · Jul 27, 2012

Adding to the first comment, you can try reading one byte at a time (declare a char variable and write there), and then use the bitwise operators >> and << to read bit by bit. Read more here: http://www.cprogramming.com/tutorial/bitwise_operators.html