2

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

我不能使用 strtol、fprintf 或 fscanf。

我要这个:-

unsigned char *hexstring = "12FF";

要转换为:-

unsigned int hexInt = 0x12FF
4

2 回答 2

3

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

以下将在使用标准库的情况下工作...在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”开头的字符串......但您可以在函数开头添加一个快速检查,然后咀嚼这些字符......

于 2013-10-24T15:43:04.463 回答
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);
于 2013-10-24T15:38:25.207 回答