迭代和比较不同尺寸的结构元素

发布于 2025-01-25 03:58:50 字数 1054 浏览 3 评论 0原文

我有一个棘手的问题,我不知道是否有任何解决方案。

基本上,我使用X-Macros填充了一个结构,例如使用以下宏:

#define X_MACRO_TABLE(_) \
_(var_1 , type1)\
_(var_2, type2)\
_(...., ....)\
_(var_n, type_n)\

我可以具有这样的输出:

    typedef struct __attribute__((packed, aligned(1)))
    {
        union {
            struct __attribute__((packed, aligned(1))) data{
                type_1 var_1;
                type_2 var_2;
                ....
                type_n var_n;
            }data_s;
            uint8 DataArray[sizeof(struct data)];
        };
    }data_t;

这是我经常做的事情,而且可以正常工作。

现在,假设我需要定义两个结构:

static data_t   DataVar;
static data_t   DataVar_max;

有什么方法使用循环或其他方法将结构的每个元素与最大值进行比较?

DataVar.var_1 > DataVar_max.var_1 ??
DataVar.var_2 > DataVar_max.var_2 ??

或通过数组,由于我知道类型维度的事实,例如,如果var_1等于uint16_t,则做类似的事情:

(DataVar.DataArray[0]+DataVar.DataArray[1]<<8) > (DataVar_max.DataArray[0]+DataVar_max.DataArray[1]<<8) ??

I've a tricky question and I don't know if there is any solution.

Basically I've populated a struct using x-macros, for example with the following macro:

#define X_MACRO_TABLE(_) \
_(var_1 , type1)\
_(var_2, type2)\
_(...., ....)\
_(var_n, type_n)\

I can have an output like that:

    typedef struct __attribute__((packed, aligned(1)))
    {
        union {
            struct __attribute__((packed, aligned(1))) data{
                type_1 var_1;
                type_2 var_2;
                ....
                type_n var_n;
            }data_s;
            uint8 DataArray[sizeof(struct data)];
        };
    }data_t;

It is something I often do and it's works fine.

Now let's say I need to define two struct:

static data_t   DataVar;
static data_t   DataVar_max;

There is any way using a loop or something to compare each element of the struct with its maximum?

DataVar.var_1 > DataVar_max.var_1 ??
DataVar.var_2 > DataVar_max.var_2 ??

Or passing through the array, due to the fact I know the types dimension, for example in case var_1 is equal to uint16_t do something like:

(DataVar.DataArray[0]+DataVar.DataArray[1]<<8) > (DataVar_max.DataArray[0]+DataVar_max.DataArray[1]<<8) ??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉城 2025-02-01 03:58:50

假设可以将类型与&gt;运算符进行比较,并且两个结构都可以初始化,则可以简单地进行:

#define COMP_MEMBERS(name, type) if (DataVar.name > DataVar_max.name) { do_something(); }
...
X_MACRO_TABLE(COMP_MEMBERS)

如果每个成员每个会员语句,则将扩展到

Assuming the types can be compared with the > operator and both structs are initialized, you can simply do:

#define COMP_MEMBERS(name, type) if (DataVar.name > DataVar_max.name) { do_something(); }
...
X_MACRO_TABLE(COMP_MEMBERS)

This will expand to an if statement per member.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文