我有 4 个 Uint32 变量,名为 lowLevelErrors1、lowLevelErrors2... 最多 4 个。这些变量上的每一位代表一个低级错误。我需要将它们映射到名为 userErrors 的 Uint64 变量。 userError 的每一位代表向用户显示的错误,可以由于 1 个或多个低级错误而设置该错误。换句话说,每个低级错误都会映射到 1 个用户错误。 2 个或更多低级错误可以映射到同一用户错误。
让我们将其缩小到 2x Uint8 低级错误和 1x Uint8 用户错误,以便我们可以看到一个示例。
示例:如果设置了以下任何低级错误 {ERR_VOLT_LOW ||错误_无电池|| ERR_NOT_CHARGING}(对应于 lowLevelErrors1 的位 0、位 2 和位 3),然后设置用户错误 US_ERR_POWER_FAIL(即 userErrors 的位 5)。
所以我能想到的唯一方法是为每个 lowLevelErrors 变量创建一个映射数组,用于映射到 userErrors 的相应位。
/* Let's say the lowLevelErrors have to be mapped like this:
lowLevelErrors1 bit maps to userError bit
0 5
1 1
2 5
3 5
4 0
5 2
6 7
7 0
lowLevelErrors2 bits maps to userError bit
0 1
1 1
2 0
3 3
4 6
5 6
6 4
7 7
*/
Uint8 lowLevelErrors1 = 0;
Uint8 lowLevelErrors2 = 0;
Uint8 userErrors = 0;
Uint8 mapLLE1[8] = {5, 1, 5, 5, 0, 2, 7, 0};
Uint8 mapLLE2[8] = {1, 1, 0, 3, 6, 6, 4, 7};
void mapErrors(void)
{
for (Uint8 bitIndex = 0; bitIndex < 8; i++)
{
if (lowLevelErrors1 && (1 << i)) //If error bit is set
{
userErrors |= 1 << mapLLE1[bitIndex]; //Set the corresponding user error
}
}
for (Uint8 bitIndex = 0; bitIndex < 8; i++)
{
if (lowLevelErrors2 && (1 << i)) //If error bit is set
{
userErrors |= 1 << mapLLE2[bitIndex]; //Set the corresponding user error
}
}
}
此实现的问题是需要 map 数组。我需要 4x uint8 array[32] = 128 uint8 变量,而微 Controller 上的内存不足。
是否有其他方法可以使用更少的 RAM 来实现相同的功能?
最佳答案
您有 128 个输入位,每个输入位都映射到从 0 到 63 的位数。因此,这就是 128 * 6 = 768 位信息,这至少需要 96 字节的存储空间,除非有某种规则的模式来存储它。
所以你至少需要96个字节;即便如此,它也会被存储为打包的 6 位整数。解压这些整数的代码的成本很可能超过通过打包它们节省的 32 个字节。
所以你基本上有三个选择:一个 128 字节数组,如你所建议的;压缩 6 字节整数;或者更容易解包的错误代码的一些常规分配(如果特定的错误代码映射是固定的,则这是不可能的)。
关于c++ - 从一个变量的位到另一个变量的有效映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30996377/