C ++将结构中的所有字节相加

C++ add up all bytes in a structure

给定一个像这样的打包结构:

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

如何对其中的所有单个字节求和?

下面是一些代码,展示了两种方法。

第一种方法更简单、更有效,但对于没有 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;
}

我只想转发给 std::accumulate:

template <typename T>
size_t sum_bytes(const T& obj) {
    const unsigned char* p = reinterpret_cast<const unsigned char*>(&obj);
    return std::accumulate(p, p + sizeof(T), 0u);
}