Advertisement

reading binary files

Started by January 19, 2000 04:00 PM
2 comments, last by +AA_970+ 24 years, 11 months ago
how do i read a single bit from a binary file? and how many bits make up a byte anyway? so far i''ve only used getc(fp); to read bytes from files, but the image data in a tga file has a 1 byte header containing individual bits of data. thanks in advance for any help
ANSI C does not provide any functions for retreiving a single bit from a binary file. The smallest chunk of data you can read is a byte (8 bits), as you know. Usually, the logical AND operator is a good way to pull individual bits out of a byte:

FILE* myfile = fopen("game.dat", "rb");
char first_byte = fgetc(myfile);

if (first_byte & 1)
{
// The first bit (bit 0) is on
}
else
{
// The first bit is off
}

if (first_byte & 32)
{
// The sixth bit (bit 5) is on
}

To determine the value to use for the second operand, use the following table. Note that this is a binary sequence.

bit 0 -> 1
bit 1 -> 2
bit 2 -> 4
bit 3 -> 8
bit 4 -> 16
bit 5 -> 32
bit 6 -> 64
bit 7 -> 128

By the way the "b" in the second operand to fopen() is very important.
Advertisement
8 bits make up a byte.

Unfortunately, you can''t load just one bit from a file. However, if you load in a byte like you already know how to do, you can mask off individual bits using the / and & operators in C.

For example, suppose that you want to know the value of the leftmost bit (most significant in this example). Then, you could say

c = getc(fp);
if( c & 0x80 )
// the bit is set
else
// the bit is not set

In case you don''t know, 0x80 is 1000 0000 in hex and so this code will only be nonzero if the first bit of the variable c is set.

I hope this helps.
If you are talking about the targa file descriptor byte, here''s how I retrieve it:

struct descriptor_byte
{
unsigned char attrib : 4;
unsigned char origin : 2;
unsigned char interleaving : 2;
};

This makes a 1 byte structure with 4 bits allocated to attribs, 2 for origin and 2 for interleaving. Just read in the byte to a structure of this type, and you can access each set of bits normally.

Good luck

Starfall

This topic is closed to new replies.

Advertisement