gpt4 book ai didi

使用预处理器的 C 中两个数组的笛卡尔积

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:08 25 4
gpt4 key购买 nike

我想用另外两个数组的笛卡尔积填充一个数组。它们包含 4 位值,这些值应该位于结果数组中元素的低半字节和高半字节。

例子:

const char a1[2] = {0x1, 0x2};
const char a2[2] = {0x3, 0x4};

const char a21[4] = {0x31, 0x32, 0x41, 0x42};

我知道我可以在运行时构造它,但我想在编译时生成数组。由于程序是用C编写的,我认为预处理器是唯一的选择。

实际的数组会比示例中的大,它们将包含 16 个元素,结果将包含 256 个元素。这就是为什么我想避免自己输入值。

我需要它来加速 16 位微 Controller 上的加密例程,因为它可以处理比 4 位半字节更大的数据。

如果解决方案适用于 2 或 3,我认为我将能够使解决方案适应 16 种元素。

最佳答案

使用 Chaos以及具有良好预处理器的编译器(例如 GCC):

#include <stdio.h>
#include <stdlib.h>

#include <chaos/preprocessor/algorithm/for_each_product.h>
#include <chaos/preprocessor/recursion/expr.h>
#include <chaos/preprocessor/seq/core.h>
#include <chaos/preprocessor/seq/elem.h>
#include <chaos/preprocessor/seq/enumerate.h>

#define A(l, h) \
const unsigned char \
a1[] = { CHAOS_PP_SEQ_ENUMERATE(l) }, \
a2[] = { CHAOS_PP_SEQ_ENUMERATE(h) }, \
a21[] = { \
CHAOS_PP_SEQ_ENUMERATE( \
CHAOS_PP_EXPR(CHAOS_PP_FOR_EACH_PRODUCT( \
B, \
((CHAOS_PP_SEQ) l) \
((CHAOS_PP_SEQ) h) \
)) \
) \
}; \
/**/
#define B(s, seq) \
(CHAOS_PP_SEQ_ELEM(0, seq) | (CHAOS_PP_SEQ_ELEM(1, seq) << 4)) \
/**/

A((0x1)(0x2), (0x3)(0x4))

#undef A
#undef B

int main() {
for (int i = 0; i != sizeof(a21) / sizeof(unsigned char); ++i) {
printf("0x%x\n", a21[i]);
}
return EXIT_SUCCESS;
}

关于使用预处理器的 C 中两个数组的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com