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

Deadly 提交于 2019-12-04 17:30:26

问题


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,

GetDisplayBytes('A');

should return `an array like this...

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?


回答1:


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

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

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

Then your GetDisplayBytes() is something like:

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]);
  }
}



回答2:


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.



来源:https://stackoverflow.com/questions/3408504/whats-the-best-way-to-do-a-lookup-table-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!