简体   繁体   English

如何将二进制 0001,0010,0100,1000 转换为 0,1,2,3 以索引 4x4 二维数组?

[英]How do you convert binary 0001,0010,0100,1000 to 0,1,2,3 to index a 4x4 2D array?

I am reading key presses from a 4x4 keypad connected to a microcontroller but since a keypad is divided into rows and columns, it only reads 0001 or 1000 etc to specify row and column.我正在从连接到微控制器的 4x4 键盘读取按键,但由于键盘分为行和列,它只能读取 0001 或 1000 等来指定行和列。

I have a character lookup table for the keypad in my main like:我的主要键盘中有一个字符查找表,例如:

char keys[4][4]={
        //       c3  c2  c1  c0
                {'1','2','3','A'},  //row4 PortA4 1000 

                {'4','5','6','B'},  //row3 PortA3 0100

                {'7','8','9','C'},  //row2 PortA2 0010

                {'*','0','#','D'}   //row1 PortA1 0001

                };

I want the inputs read from the keypad to be able to directly index this table and print out said character, but naturally, any number above 3 is out of bounds.我希望从键盘读取的输入能够直接索引该表并打印出所述字符,但自然地,任何高于 3 的数字都超出范围。 I want to be able to use something like我希望能够使用类似的东西

printf("Key Pressed: %c",keys[indexrow][indexcolumn]);

but right now I have it hardcoded as follows:但现在我将其硬编码如下:

...

while(1)
    {
        //begin polling
        row_data=0x01;//bottom row
        bus.IOWrite(PortA,row_data);
        column_data=b&bus.IORead(PortB);
        if((column_data & b)!=0)
        {
            //printf("Keypress detected @row %0b @column %0b",row_data,column_data);
            switch(column_data)
            {
                case 0x01:printf("Key Pressed: D");break;
                case 0x02:printf("Key Pressed: #");break;
                case 0x04:printf("Key Pressed: 0");break;
                case 0x08:printf("Key Pressed: *");break;
                default: break;
            }

        }
.
.
.

I suppose it could be simpler to just create an 8x8 table with lots of empty spaces within, but that would not be as pleasing to look at.我想创建一个 8x8 的表可能会更简单,里面有很多空白,但这看起来不那么令人愉快。

You switch statement could help you derive an index into your 2-dimensional array like this:您的switch语句可以帮助您将索引导出到二维数组中,如下所示:

            switch(column_data)
            {
                case 0x01:column_index=0;break;
                case 0x02:column_index=1;break;
                case 0x04:column_index=2;break;
                case 0x08:column_index=3;break;
                default: /* probably needs handling here */ break;
            }

... but, what happens when more than one button is pressed. ...但是,当按下多个按钮时会发生什么。

You could write a code to convert the number format您可以编写代码来转换数字格式

# include <stdio.h>

int main()
{
  int numberToBeConverted = 0x08;
  int i,j;
  for(i=numberToBeConverted, j=1; i!=0;i/=2,j++)
  {
    if(i&1==1)
    {
      printf("%d\n",j);
      //Whatever you want to do with the key thats pressed
    }

  }
  return 0;
}

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

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