Serializing bit field structures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • (2b|!2b)==?

    #1

    Serializing bit field structures

    I have a struct declared as follows:

    struct RecordType1
    {
    unsigned int dt : 24; //3 bytes
    unsigned int ts : 16; //2 bytes
    unsigned int lsp : 24; //3 bytes (float value represented as int)
    unsigned int lst : 16; //2 bytes
    unsigned int lsv : 16; //2 bytes
    unsigned int x1 : 24; //3 bytes (float value represented as int)
    unsigned int x2 : 24; //3 bytes (float value represented as int)
    unsigned int x3 : 24; //3 bytes (float value represented as int)
    unsigned int x4 : 24; //3 bytes (float value represented as int)
    unsigned int bv : 16; //2 bytes
    unsigned int ak : 24; //3 bytes (float value represented as int)
    unsigned int av : 16; //2 bytes
    unsigned int cv : 24; //3 bytes
    };

    I need to serialize this struct by packing the bits into a contiguous
    byte array, and then read it back from the byte array. I cant use
    memcpy/sizeof because of boundary alignment ...

    I'd appreciate if anyone can show me how to do this. Ieally, I would
    like to this in a cross platform (i.e. "ENDIAN-ness" agnostic) way.
  • .rhavin grobert

    #2
    Re: Serializing bit field structures

    On 22 Okt., 10:03, James Kanze <james.ka...@gm ail.comwrote:
    [...] since generally the compiler won't allocate a bit field
    in a way that would cross a 32 bit boundary. [...] But there's
    rarely any sense in having bit fields larger than 8 bits.)
    shure? consider:

    typedef unsigned __int64 QUAD;

    #pragma pack (push, 1)
    struct foo {
    union {
    QUAD qData;
    struct {
    QUAD nFirstNibble : 4;
    QUAD nSecondNibble : 4;
    QUAD nThirdNibble : 4;
    QUAD nBloodyRest : 54;
    };
    };
    };
    #pragma pack (pop)

    Comment

    • Nick Keighley

      #3
      Re: Serializing bit field structures

      On 22 Oct, 17:31, ".rhavin grobert" <cl...@yahoo.de wrote:
      On 22 Okt., 10:03, James Kanze <james.ka...@gm ail.comwrote:
      >
      [...] since generally the compiler won't allocate a bit field
      in a way that would cross a 32 bit boundary. [...] But there's
      rarely any sense in having bit fields larger than 8 bits.)
      >
      shure? consider:
      >
      typedef unsigned __int64 QUAD;
      eek! I suppose since you've hidden __int64 behind
      a typedef you can live with that

      #pragma pack (push, 1)
      eek! ** 2

      the guy want's *portable* stuff! How many platforms
      does this work on?

      struct foo {
        union {
          QUAD qData;
          struct {
            QUAD nFirstNibble  :  4;
            QUAD nSecondNibble :  4;
            QUAD nThirdNibble  :  4;
            QUAD nBloodyRest   : 54;
          };
        };};
      >
      #pragma pack (pop)
      --
      Nick Keighley

      Comment

      Working...