我有一个 4 字节的十六进制字符字符串,我想将它们转换为 c 中的 2 字节整数。
我无法使用 strtol、fprintf 或 fscanf。
我想要这个:-
unsigned char *hexstring = "12FF";
要转换为:-
unsigned int hexInt = 0x12FF
最佳答案
编辑:哦,只需阅读 azmuhak 的建议链接。这绝对是该问题的重复。 azmuhak 链接中的答案也更完整,因为它处理“0x”前缀...
以下内容将使用标准库与 out 一起使用... 请参阅 ideone here
#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”开头的字符串...但您可以在函数的开头添加对此的快速检查,然后只是咀嚼这些字符...
关于c - C 中十六进制字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569965/