0

We're doing some experiment on random number. The data given me is stored in a .bin file, and according to the provider, it's stored in independent bits, that is, every bit is the supposed bool random variable.

Now I would like to use this input in program, but as bool take 1 BYTE and int take 4 bytes, I don't know how to read it into a variable in C++. And it seems that the ifstream.read(s,n) also only takes n as number of char.

Is there any way to read bit data from file? Thank you!

Mike Wong
  • 121
  • 1
  • 3
  • 4
    You do realize that chars and ints and bytes consist of bits, right? You can't read one bit at a time, but you can read 8 bits at a time. Think of `ifstream.read(s,n)` as reading `8*n` bits, rather than `n` bytes. – Igor Tandetnik Aug 19 '14 at 21:05

2 Answers2

8

If every char is 8 bits, then you can discover the state of each bit like this:

// @param bit = 0 - 7
inline bool get_bit(char c, int bit)
{
    return (c >> n) & 1;
}
Galik
  • 47,303
  • 4
  • 80
  • 117
5

The smallest unit of information that can be read from a file is a char (8 bits1). To extract a particular bit from a char, you can do something like:

char c = 0xa5;
int n = 2;
int bit = (c >> n) & 1;
printf("bit = %d\n", bit);

1If I don't include this, then somebody will point out that a char doesn't always have to be 8 bits, and it depends on CHAR_BIT as defined by your compiler, but on all reasonable platforms today, a char is 8 bits.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285