CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2002
    Posts
    69

    storing structs with bit-fields on disk minimally

    Here's my problem :

    i have a structure, defined as follows:

    Code:
    #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
    Code:
    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

  2. #2
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    You don't have to unpack it into an unsigned long (not short): just use a union.
    Code:
    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
    Succinct is verbose for terse

  3. #3
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    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.
    Succinct is verbose for terse

  4. #4
    Join Date
    Jul 2002
    Posts
    69
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured