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

Mak*_*ges -1 c++ struct osdev

给定一个这样的压缩结构:

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

如何将其中的所有单个字节相加?

Bar*_*rry 6

我只想转发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);
}
Run Code Online (Sandbox Code Playgroud)

  • @Makerimages事情就像你真正想做的事情以及你所拥有的限制一样. (3认同)

Jer*_*ner 5

下面是一些代码,显示了两种方法.

第一种方法更容易,更有效,但是对于没有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;
}
Run Code Online (Sandbox Code Playgroud)