Как преобразовать строки в массиве в целые числа без знака? - PullRequest
0 голосов
/ 23 мая 2018

У меня есть следующий код:

char switch_list[] = {
    "PINB >> 7", 
    "PIND >> 1", 
    "PINB >> 1", 
    "PIND >> 0}"
};

void values(void){
    uint8_t switch_value = 0;
        if (i == 0){
            switch_value = (PINB >> 7) & 1; 
        }
        if (i == 1){
            switch_value = (PIND >> 1) & 1;
        }
        if (i == 2){
            switch_value = (PINB >> 1) & 1;
        }
        if (i == 3){
            switch_value = (PIND >> 0) & 1;
        }
        SOME OTHER OPERATIONS GO HERE
}

Мне нужно как-то интерпретировать значения switch_list как целые числа без знака, но я не могу внести какие-либо изменения в массив (этодолжен остаться массив символов). PINB и другие определили 8-битное значение в библиотеках.Я хотел бы создать цикл for, который будет выглядеть примерно так:

uint8_t switch_value = 0;
    for (int i = 0, i < sizeof(switch_list)/sizeof(switch_list[0]); i++){
            switch_value = **********[i] & 1; 
         SOME OTHER OPERATIONS GO HERE
        }
}

Где ********* - то же самое, что switch_list , но вместо charтип, это uint8_t .Кто-нибудь может дать какие-нибудь советы?

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Предполагая, что PINx штуковины будут оцениваться как тип PIN_T, вы можете сделать:

#include <stdlib.h> /* for size_t */
#include <inttypes.h> /* for uint8_t */

/* other include here */


struct switch_s
{
  PIN_T * ppin;
  uint8_t offset;
};

struct switch_s switches[] =
{
  {&PINB, 7},
  {&PIND, 1},
  {&PINB, 1},
  {&PIND, 0},
  /* more here */
};

int main(void)
{ 
  for (size_t i; i < sizeof switches / sizeof *switches; ++i)
  {
    uint8_t switch_value = (*switches[i].ppin >> switches[i].offset) & 1;

    /* Work with switch_value here ... */
  }
}
0 голосов
/ 23 мая 2018

Вы можете использовать свои знания о массиве и создать функцию для преобразования значений из "PINB >> 7" в PINB >> 7.Я сделал следующие предположения:

  1. Строка всегда начинается с «PIN», а затем имеет «B» или «D» (может быть легко изменено)
  2. Строка будетзатем выполните операцию (в настоящее время я поддерживаю только «>>», но это тоже можно легко изменить)
  3. Последний символ в строке представляет собой число из 1 символа (опять же, его можно изменить в соответствии с вашими знаниями острока)

Используя это, я могу создать convert функцию

unsigned int convert(char * p);

/* PINB and the others have defined 8 bit value in the libraries
   so I'm making up their values here for convenience */
unsigned int PINB = 1024;
unsigned int PIND = 2048;

int main(){
    // deleted your ending }
    // and changed the type of the array
    char* switch_list[] = {
        "PINB >> 7", 
        "PIND >> 1", 
        "PINB >> 1", 
        "PIND >> 0"
    };

    unsigned int switch_value;
    // , should be ;
    // don't compare signed with unsigned
    for (unsigned int i = 0; i < sizeof(switch_list)/sizeof(switch_list[0]); i++){
        switch_value = convert(switch_list[i]); 
        printf("%u\n", switch_value);
    }

    return 0;
}

// assuming string must be exactly long as "PINB >> 7"
unsigned int convert(char * p){
    if(!p || strlen(p) != strlen("PINB >> 7")){
        printf("error\n");
        return (unsigned)-1;
    }

    unsigned int n;
    // use a string compare or, in your case, since only the 4th char is different:
    if(p[3] == 'B')
        n = PINB;
    if(p[3] == 'D')
        n = PIND;
    // note I'm not handling a case where the 4th letter isn't {'B', 'D'}, according to my assumption (the 1st).

    // use your knowledge about the string inside switch_list
    return n >> (p[strlen(p) - 1] - '0');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...