将十进制转换为十六进制是截断第一个数字

时间:2017-04-12 08:37:39

标签: c string char int hex

我有一个将十进制转换为十六进制的函数,但它在返回十六进制字符串时截断了第一个字符。为什么以及如何截断返回的字符串?

这是我解剖的字符串:

str = "095154.000,4506.1389N,07389.6017W,2.00,290.0,3,299.12,0.08,0.04,120417,05";

代码:

char str[90];
char** tokens;
tokens = str_split(str, ',');

strncpy(tempTime, *(tokens)+9, 6);tempTime[7]="\0";

num = atoi(tempTime);
char hex_response[(sizeof(long int) * CHAR_BIT / 4) + 1];
printf("%s", int_hex(num, hex_response));

char* int_hex(long int num, char* hextresponse)
{
    sprintf(hex_response, "%lX", (unsigned long)num);

    return hextresponse;
}

hex_response返回73B2,它应返回173B2

1 个答案:

答案 0 :(得分:1)

解决方案是更改以下代码

num = atoi(tempTime);  // String to int conversion

num = atol(tempTime);  // String to long conversion