简体   繁体   English

C语言中的地图编号

[英]Map numbers in C language

How can i map numbers like this: 我如何映射这样的数字:

1 => 0x01;
2 => 0x03;
3 => 0x07;
4 => 0x0F;
....
8 => 0xFF;

I have only 8 numbers to map and i need this for my RT embedded system so the solution must be efficient. 我只有8个要映射的数字,而我的RT嵌入式系统需要这个数字,因此解决方案必须高效。 Is there a way to implement this using ENUM or DEFINE? 有没有一种方法可以使用ENUM或DEFINE来实现? I don't want to use switch statement. 我不想使用switch语句。 Should i use an array: 我应该使用数组吗:

BYTE bMap[8] = 
{
    0x01,
    0x03,
    0x07,
    0x0F,
    ....
    0xFF,
}

or is there another way? 还是有另一种方法? Thank you! 谢谢! Max. 最高

The two most obvious solutions would be: 两个最明显的解决方案是:

  1. Use an array. 使用数组。 const uint8_t masks[] = { 1, 3, ... } . const uint8_t masks[] = { 1, 3, ... }
  2. Your mask seems to be "the i + 1 rightmost bits should be set", so you can trivally compute that at runtime using (1 << (i + 1)) - 1 which is easier to implement and less error-prone. 您的掩码似乎是“应设置第i + 1最右边的位”,因此您可以在运行时使用(1 << (i + 1)) - 1进行简单的计算,这更易于实现且不易出错。

If you only have 8 values and that's not going to change, use the array. 如果只有8个值并且不会改变,请使用数组。 But note that the mapping would be 0=>0x01, 1=>0x03, ... etc., because C indexing is zero-based. 但是请注意,映射将是0=>0x01, 1=>0x03, ...等,因为C索引是从零开始的。

Also, look for a pattern in your numbers: you could find a logic or arithmetic operation that will set the least significant N bits in a byte. 另外,在您的数字中寻找一种模式:您可以找到将字节中的最低有效N位设置为1的逻辑或算术运算。 Ie N => (2 * N) -1 即N =>(2 * N)-1

There's nothing wrong with using the lookup table to get your numbers but you could consider another approach. 使用查找表获取数字没有 ,但是您可以考虑使用另一种方法。

If you're simply looping through those values in order, each one can be obtained by left-shifting the previous and setting the low order bit to 1: 如果您只是按顺序遍历这些值,则可以通过左移前一个值并将低位设置为1来获得每个值:

      0000 0001 (x01)

<< 1: 0000 0010
 | 1: 0000 0011 (x03)

<< 1: 0000 0110
 | 1: 0000 0111 (x07)

<< 1: 0000 1110
 | 1: 0000 1111 (x0f)

<< 1: 0001 1110
 | 1: 0001 1111 (x1f)

So, something like: 因此,类似:

for (unsigned int i = 1; i < 0x100; i = (i << 1) | 1) ...

should do the trick. 应该可以。

The only possible advantage I can see that may have would be not having to go out to memory for a lookup table. 唯一可能的优势,我可以看到, 可能将不必出门到内存中以便查找表。 Depending on your hardware architecture, that may or may not be a problem. 根据您的硬件体系结构,这可能是问题,也可能不是问题。

The following complete program: 以下完整程序:

#include <stdio.h>

int main (void) {
    unsigned int i;
    for (i = 1; i < 0x100; i = (i << 1) | 1)
        printf ("%02x ", i);
    putchar('\n');
    return 0;
}

shows it in action: 显示它的作用:

01 03 07 0f 1f 3f 7f ff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM