C 中十六进制字符串转换为整数

问题描述 投票:0回答:3

我有一个 4 字节的十六进制字符字符串,我想将它们转换为 c 中的 2 字节整数。

我无法使用 strtol、fprintf 或 fscanf。

我想要这个:-

unsigned char *hexstring = "12FF";

要转换成这样:-

unsigned int hexInt = 0x12FF
c converters
3个回答
3
投票

编辑:哦,只需阅读 azmuhak 的建议链接。这绝对是该问题的重复。 azmuhak 链接中的答案也更完整,因为它处理“0x”前缀...

以下内容将使用标准库与 out 一起使用...... 在 ideone 上查看这里

#include <stdio.h>

#define ASCII_0_VALU 48
#define ASCII_9_VALU 57
#define ASCII_A_VALU 65
#define ASCII_F_VALU 70

unsigned int HexStringToUInt(char const* hexstring)
{
    unsigned int result = 0;
    char const *c = hexstring;
    char thisC;

    while( (thisC = *c) != NULL )
    {
        unsigned int add;
        thisC = toupper(thisC);

        result <<= 4;

        if( thisC >= ASCII_0_VALU &&  thisC <= ASCII_9_VALU )
            add = thisC - ASCII_0_VALU;
        else if( thisC >= ASCII_A_VALU && thisC <= ASCII_F_VALU)
            add = thisC - ASCII_A_VALU + 10;
        else
        {
            printf("Unrecognised hex character \"%c\"\n", thisC);
            exit(-1);
        }

        result += add;
        ++c;
    }

    return result;  
}

int main(void) 
{
    printf("\nANSWER(\"12FF\"): %d\n", HexStringToUInt("12FF"));
    printf("\nANSWER(\"abcd\"): %d\n", HexStringToUInt("abcd"));

    return 0;
}

代码可以变得更高效,我使用

toupper
库函数,但你可以轻松地自己实现......

此外,这不会解析以“0x”开头的字符串...但是您可以在函数的开头添加对此的快速检查,然后只是咀嚼这些字符...


1
投票

您可以使用 stdlib.h 中的 strtol()

http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm

char str[30] = "0x12FF";
char **ptr;
long val;
val = strtol(str, ptr, 16);

0
投票
uint64_t hextou64(uint8_t *charnibble)
    {
    uint64_t n = 0;
    uint8_t c, v;
    for (uint8_t i = 0; i < 16; i++)
        {
        c = *(charnibble + i);
        v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
        n = (n << 4) | (uint64_t)v;
        }
    return n;
    }
© www.soinside.com 2019 - 2024. All rights reserved.