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

C++ C++;将结构中的所有字节相加,c++,struct,osdev,C++,Struct,Osdev,给定这样的压缩结构: struct RSDPDescriptor { char Signature[8]; uint8_t Checksum; char OEMID[6]; uint8_t Revision; uint32_t RsdtAddress; } __attribute__ ((packed)); 如何对其中的所有单个字节求和?以下是一些代码,展示了两种方法 第一种方法更简单、更有效,但对于没有packed属性的结构,它会给出错误的结果(因为它

给定这样的压缩结构:

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;
}
#包括
#包括
模板int CountBytes(常量T&T)
{
整数计数=0;
const unsigned char*p=重新解释强制转换(&t);
对于(int i=0;i我只希望:

模板
大小总和字节(常量t&obj){
const unsigned char*p=重新解释强制转换(&obj);
返回标准::累加(p,p+sizeof(T),0u);
}

All-like-All或All-like
Revision+RsdtAddress+Checksum+…
?或者仅仅是总大小还是什么?您可以将每个元素的大小相加。请注意,您不能只要求
sizeof(RSDPDescriptor)
,因为这将包括填充。@Cyber:
\uuuu属性((打包))
有填充吗?@inetknght很好,你说得对!@Barry是所有字节的总和,而不是字节数。内核编程-不能使用std::stuff。@Makerimages像你实际想做的事情和问题中的限制一样。@Makerimages
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);
}