bit fields and .bin files...

I have some code I am using to take an object of a specific type (e.g., a char or an int) and, using a struct whose members are "unsigned"s of length 1.
Example:

1
2
3
4
5
6
7
8
9
10
11
struct cbin
{
   unsigned b0:1,
            b1:1,
            b2:1,
            b3:1,
            b4:1,
            b5:1,
            b6:1,
            b7:1;
};


And the conversion from an input character would be performed via the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
cbin conv_char(char& ch)
{
   cbin X;

   char* V = &ch;

   X.b0 = ((*V >> 0) & 1)?1:0;
   X.b1 = ((*V >> 1) & 1)?1:0;
   X.b2 = ((*V >> 2) & 1)?1:0;
   X.b3 = ((*V >> 3) & 1)?1:0;
   X.b4 = ((*V >> 4) & 1)?1:0;
   X.b5 = ((*V >> 5) & 1)?1:0;
   X.b6 = ((*V >> 6) & 1)?1:0;
   X.b7 = ((*V >> 7) & 1)?1:0; 

   return X;
}


When I try to output the results of several of these operations to a .bin file, with the following function:

1
2
3
4
void print_bin2file(cbin& X, std::ofstream* mdats)
{
   *mdats<<X.b0<<X.b1<<X.b2<<X.b3<<X.b4<<X.b5<<X.b6<<X.b7;
}


I try to open the file in Notepad, and I get a bunch of 1's and 0's - shouldn't I be getting a mush of blank spaces and funky Chinese-looking characters?

Am I mistakenly outputting actual "int" 1s and 0s, instead of single bits to the file?
Yes, they are unsigned (int)s so when you output them, you are outputting basically an unsigned int where the compiler only cares about the first bit. You would need to open your file in binary mode to do what you are describing.
You need to "un"convert back to a char and then output the char.

Bitfields are only useful in the abstract. They are not safe for binary formatting, unless you are targeting a specific version of a specific compiler.

Also, your code is overdone. To simply extract a bit:
7
8
9
   X.b0 = ( *V       & 1);
   X.b1 = ((*V >> 1) & 1);
   ...

Hope this helps.
Last edited on
Thanks, guys...

Tried outputting in binary mode, however, got the same result...

outputted the char, and it seemed to work...
Topic archived. No new replies allowed.