Click to See Complete Forum and Search --> : storing structs with bit-fields on disk minimally


theperplepigg
November 12th, 2002, 11:11 AM
Here's my problem :

i have a structure, defined as follows:


#define MAPSIZE 14
struct node
{
unsigned short leftMap :MAPSIZE; // map to left input
unsigned short rightMap :MAPSIZE; // map to right input
unsigned short leftValue :1; // left value = 0 || 1
unsigned short rightValue :1; // right value = 0 || 1
unsigned short out :1; // output of node
};


(yes, i know i still have 1 bit to play with, just don't need it)

and an array of these nodes. i want to be able to store this array on disk in just as little space as i do in memory(32 bits*numNodes). is there any slick way to write/read it, such as

nodes[i] >> out; // to write
out >> nodes[i]; // to read

or do i have to go about writing read/write functions that will pack an unsigned short and write that to disk? thanks.

--paul

cup
November 12th, 2002, 11:52 AM
You don't have to unpack it into an unsigned long (not short): just use a union.

union
{
struct node
{
unsigned short leftMap :MAPSIZE; // map to left input
unsigned short rightMap :MAPSIZE; // map to right input
unsigned short leftValue :1; // left value = 0 || 1
unsigned short rightValue :1; // right value = 0 || 1
unsigned short out :1; // output of node
} bitty;

unsigned long holy;
} nodes[NODE_MAX];

out << nodes[i].holy; // to write
out >> nodes[i].holy; // to read

cup
November 12th, 2002, 11:56 AM
If you want to use as little space as possible, use the C routines fopen, fread, fwrite and fclose. Then a 32 bit word will only take up 32 bits. C++ isn't very good for binary input.

theperplepigg
November 12th, 2002, 01:50 PM
thanks, i will try your suggestions. this isn't an issue just yet, but i was thinking about it, since it'll come up next week sometime when i do that part of the program.

--paul