Search code examples
c++structosdev

C++ add up all bytes in a structure


Given a packed struct like this:

struct RSDPDescriptor {
    char Signature[8];
    uint8_t Checksum;
    char OEMID[6];
    uint8_t Revision;
    uint32_t RsdtAddress;
} __attribute__ ((packed));

How can I sum all of the individual bytes in it?


Solution

  • Here is some code that shows two ways to do it.

    The first way is easier and more efficient, but will give the wrong result for a struct that doesn't have the packed attribute (since it will incorrectly include the padding bytes in its tally).

    The second approach will work on any struct, padded or packed.

    #include <stdio.h>
    #include <stdlib.h>
    
    template<typename T> int CountBytes(const T & t)
    {
       int count = 0;
       const unsigned char * p = reinterpret_cast<const unsigned char *>(&t);
       for (int i=0; i<sizeof(t); i++) count += p[i];
       return count;
    }
    
    struct RSDPDescriptor {
        char Signature[8];
        unsigned char Checksum;
        char OEMID[6];
        unsigned char Revision;
        unsigned int RsdtAddress;
    } __attribute__ ((packed));
    
    int main(int, char **)
    {
       struct RSDPDescriptor x;
    
       int byteCountFast = CountBytes(x);
       printf("Fast result (only works correctly if the struct is packed) is:  %i\n", byteCountFast);
    
       int byteCountSafe = CountBytes(x.Signature) + CountBytes(x.Checksum) + CountBytes(x.OEMID) + CountBytes(x.Revision) + CountBytes(x.RsdtAddress);
       printf("Safe result (will work even if there is padding) is:  %i\n", byteCountSafe);
    
       return 0;
    }