将十六进制值转换为 C 中的十进制值

时间:2021-06-10 23:28:55

标签: c string hex decimal

我尝试了很多来自 SO 的想法。当我在此处 onlinegdb 对其进行测试时,其中一个工作正常(HEX 31 的输出为 DEC 49)。 但是,当我在我的应用程序中实现它时,它并没有产生相同的结果。 (再次输出为 31 为 31)。

想法是使用字符串值(充满十六进制对); 一个例子; 313030311b5b324a1b5b324a534f495f303032371b

我需要将每个整数对 (HEX) 转换为等价的十进制值。 例如

HEX => DEC
31  => 49
30  => 48

然后我将使用 UART 逐个值发送 DEC 值。

我测试行为的代码如下和here; 但是,它不一定是那个代码,只要它能完成工作,我愿意接受所有建议。

#include <stdio.h>
    
int isHexaDigit(char p) {
    return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}
    
int main(int argc, char** argv) 
{ 
    char * str = "31";
    char t[]="31";
    char* p = t;
    char val[3]; // 2 hexa digit 
    val[2] = 0;  //and the final \0 for a string
    int number; 
        
    while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {
        val[0] = *p;
        val[1] = *(p+1);
    
        sscanf(val,"%X", &number);    // <---- Read hexa string into number
        printf("\nNum=%i",number);    // <---- Display number to decimal.
                  
        p++;
        //p++;
        if (!*p) break;
        p++;
    }
    return 0; 
} 

编辑 我最小化了代码。 奇数字符串暂时被忽略。 代码逐字节发送数据。在终端应用中, 我得到的值为十六进制,例如HEX 31 而不是 DEC 49。它们实际上是相同的。但是,我使用的设备需要值的 DEC 49 版本(即 ASCII = 1)

enter image description here

高度赞赏任何指针。

1 个答案:

答案 0 :(得分:2)

您可以使用 strtol 函数将十六进制字符串转换为二进制,然后在一行中将其转换为十进制字符串:

snprintf(str_dec, 4, "%ld", strtol(str_hex, NULL, 16));

您的代码变为:

#include <stdio.h>
#include <stdlib.h>

int isHexaDigit(char p) {
    return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}

int main(int argc, char** argv)
{
    char * str = "31";
    char t[]="31";
    char* p = t;

    char str_hex[3] = {0,};
    char str_dec[4] = {0,};

    while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {

        str_hex[0] = *p;
        str_hex[1] = *(p+1);

        /* Convert hex string to decimal string */
        snprintf(str_dec, 4, "%ld", strtol(str_hex, NULL, 16));

        printf("str_dec = %s\n", str_dec);

        /* Send the decimal string over UART1 */
        if (str_dec[0]) UART1_Write(str_dec[0]);
        if (str_dec[1]) UART1_Write(str_dec[1]);
        if (str_dec[2]) UART1_Write(str_dec[2]);

        /* Reset str_dec variable */
        str_dec[0] = 0;
        str_dec[1] = 0;
        str_dec[2] = 0;

        p++;
        if (!*p) break;
        p++;
    }
    return 0;
}
相关问题