Main Page. VBA, ASP, Visual Basic 6.0, and VB.net. Visual C++, C#, C++, C. HTML and maybe javascript. Forum,Games and Jokes, other stuff. Submit a Tutorial Today!
Accessing Binary Data With C

Many times in C, data must be accessed in a bitwise fashion. Usually, programmers will use the char type to represent a quick and easy byte. However, when bit flipping is necessary, this bandaid solution fails to deliver. Using the following technique will create a variable type that lets the programmer work with bits on an individual basis.


struct binary{
  union the_data{
    unsigned b_0:1;
    unsigned b_1:1;
    unsigned b_2:1;
    unsigned b_3:1;
    unsigned b_4:1;
    unsigned b_5:1;
    unsigned b_6:1;
    unsigned b_7:1;
    unsigned char all:8;
  } data;
};

To use the structure:

struct binary variable_name;
variable_name.data.all = 1;
printf("%u\n", variable_name.data.b_7); /* Depending on the machine, b_7 might be 1, or b_0 might be 1. */

A link that provides more information on bit fields.

<--Return to C Section

 

Binary Central by Anman: "http://www15.brinkster.com/anman/"