C语言 在 C 中进行查找表的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3408504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:05:22  来源:igfitidea点击:

What's the best way to do a lookup table in C?

clookup-tables

提问by PICyourBrain

I am working on an embedded C project. I have an LCD display and for each character there is a 5x7 dot matrix. To display a specific character you have to shift in 5 bytes that correlate with the dots to turn on. So I need to make some kind of look-up table with a key where I can pass in an ASCII character, and get an array of 5 bytes returned... For example, a call to this function like this,

我正在研究一个嵌入式 C 项目。我有一个 LCD 显示屏,每个字符都有一个 5x7 点阵。要显示特定字符​​,您必须移动与要打开的点相关的 5 个字节。所以我需要用一个键创建某种查找表,我可以在其中传入一个 ASCII 字符,并返回一个 5 个字节的数组......例如,像这样调用这个函数,

GetDisplayBytes('A');

GetDisplayBytes('A');

should return `an array like this...

应该返回一个像这样的数组......

C[0] = 0x7E : C[1] = 0x90 : C[2] = 0x90 : C[3] = 0x90 : C[4] = 0x7E

C[0] = 0x7E : C[1] = 0x90 : C[2] = 0x90 : C[3] = 0x90 : C[4] = 0x7E

What would be the best way to do this in C?

在 C 中执行此操作的最佳方法是什么?

回答by Carl Norum

I would make arrays for the contiguous ASCII blocks you want to use. data. Something like this:

我会为您要使用的连续 ASCII 块制作数组。数据。像这样的东西:

uint8_t displayBytesLetters[] = 
{
  0x73, 0x90, 0x90, 0x90, 0x73, // 'A'
  .
  .
  .
};

uint8_t displayBytesDigits[] = 
{
  0x12, 0x15, 0x25, 0x58, 0x80, // '0'
  .
  .
  .
};

Then your GetDisplayBytes()is something like:

然后你GetDisplayBytes()是这样的:

uint8_t *GetDisplayBytes(char c)
{
  if (isdigit(c))
    return &displayBytes[5*(c - '0')];
  else if (isupper(c))
    return &displayBytes[5*(c - 'A')];
  else
    return NULL;
}

Pass the returned pointer to whatever function outputs the data:

将返回的指针传递给任何输出数据的函数:

void DoDisplay(uint8_t *displayBytes)
{
  int i;
  for (i = 0; i < 5; i++) 
  {
     SendOutput(displayBytes[i]);
  }
}

回答by James Curran

typedef char LCDDATA[5];   

LCDDATA lcdTable[256] = { {0,0,0,0,0},  // char 0
                          {.....},       // char 1
                        }

LCDDATA GetDisplayBytes(char chr)
{
     return lcdTable[chr];
}

This is basically making an array of arrays.

这基本上是制作一个数组数组。