c - 如何将数组中的字符串转换为无符号整数?

标签 c type-conversion

我有以下代码:

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 值解释为无符号整数,但我无法对数组进行任何更改(它需要保留为 char 数组)。 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。谁能提供任何提示?

最佳答案

您可以利用您对数组的了解并创建一个函数,将您的值从 "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');
}

关于c - 如何将数组中的字符串转换为无符号整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481907/

相关文章:

c# - 将 WMI CimType 转换为 System.Type

c - 哈希函数中的 get16bits 宏

c - CUDA 内联汇编从 GAS 到 Intel 的翻译

c - 在另一个字符串的中间添加新字符串 - c

c - 我不明白这个程序是如何工作的

c - 混合标准和精确宽度类型

c - 将 256 位 key 打入 32 位轮 key 的问题

java - JSON:将对象转换为数组

javascript - Typeof 错误 - 返回 NaN,即使两者都是数字

c++ - reinterpret_cast 是否保证不更改源指针的地址?