I'm using a function which receives a const char*.
我正在使用一个接收const char *的函数。
long hex2long(const char* hexString)
I have that hexString in unsigned int format and need to convert it to const char* to use that function.
我有无符号int格式的hexString,需要将它转换为const char *才能使用该函数。
I have also tried to use strtol() but it's the same problem.
我也试过使用strtol(),但这是同样的问题。
Any idea?
This is the function:
这是功能:
static const long hextable[] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
-1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
-1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1
};
long hex2long(const char* hexString)
{
long ret = 0;
while (*hexString && ret >= 0)
{
ret = (ret << 4) | hextable[*hexString++];
}
return ret;
}
1 个解决方案
#1
Your question is confused. Your function parses the hexadecimal representation of a number and returns the value as a long
. You should stop parsing when you encounter a non-hexadecimal digit, and you could ignore any leading white space characters. The library function strtol()
does just that, with a value of 16
for the last argument (conversion base).
你的问题很困惑。您的函数解析数字的十六进制表示形式,并将值作为long返回。遇到非十六进制数字时应该停止解析,并且可以忽略任何前导空白字符。库函数strtol()就是这样做的,最后一个参数(转换基数)的值为16。
What else are you trying to achieve?
还有什么想要实现的?
#1
Your question is confused. Your function parses the hexadecimal representation of a number and returns the value as a long
. You should stop parsing when you encounter a non-hexadecimal digit, and you could ignore any leading white space characters. The library function strtol()
does just that, with a value of 16
for the last argument (conversion base).
你的问题很困惑。您的函数解析数字的十六进制表示形式,并将值作为long返回。遇到非十六进制数字时应该停止解析,并且可以忽略任何前导空白字符。库函数strtol()就是这样做的,最后一个参数(转换基数)的值为16。
What else are you trying to achieve?
还有什么想要实现的?