struct - C++ add up all bytes in a structure -


given packed struct this:

struct rsdpdescriptor {     char signature[8];     uint8_t checksum;     char oemid[6];     uint8_t revision;     uint32_t rsdtaddress; } __attribute__ ((packed)); 

how can sum of individual bytes in it?

here code shows 2 ways it.

the first way easier , more efficient, give wrong result struct doesn't have packed attribute (since incorrectly include padding bytes in tally).

the second approach work on 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);    (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 struct 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 if there padding) is:  %i\n", bytecountsafe);     return 0; } 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -