1. _ltoa函数
描述:将long的类型的数据l,按照radix的格式(16进制或者10进制的格式)转换成字符串存到数据buf[n]中。
/*********************************************************************
* @fn _ltoa
*
* @brief
*
* convert a long unsigned int to a string.
*
* @param l - long to convert
* @param buf - buffer to convert to
* @param radix - 10 dec, 16 hex
*
* @return pointer to buffer
*/
unsigned char * _ltoa(unsigned long l, unsigned char *buf, unsigned char radix)
{
#if defined( __GNUC__ )
return ( (char*)ltoa( l, buf, radix ) );
#else
unsigned char tmp1[10] = "", tmp2[10] = "", tmp3[10] = "";
unsigned short num1, num2, num3;
unsigned char i;
buf[0] = '\0';
if ( radix == 10 )
{
num1 = l % 10000;
num2 = (l / 10000) % 10000;
num3 = (unsigned short)(l / 100000000);
if (num3) _itoa(num3, tmp3, 10);
if (num2) _itoa(num2, tmp2, 10);
if (num1) _itoa(num1, tmp1, 10);
if (num3)
{
strcpy((char*)buf, (char const*)tmp3);
for (i = 0; i < 4 - strlen((char const*)tmp2); i++)
strcat((char*)buf, "0");
}
strcat((char*)buf, (char const*)tmp2);
if (num3 || num2)
{
for (i = 0; i < 4 - strlen((char const*)tmp1); i++)
strcat((char*)buf, "0");
}
strcat((char*)buf, (char const*)tmp1);
if (!num3 && !num2 && !num1)
strcpy((char*)buf, "0");
}
else if ( radix == 16 )
{
num1 = l & 0x0000FFFF;
num2 = l >> 16;
if (num2) _itoa(num2, tmp2, 16);
if (num1) _itoa(num1, tmp1, 16);
if (num2)
{
strcpy((char*)buf,(char const*)tmp2);
for (i = 0; i < 4 - strlen((char const*)tmp1); i++)
strcat((char*)buf, "0");
}
strcat((char*)buf, (char const*)tmp1);
if (!num2 && !num1)
strcpy((char*)buf, "0");
}
else
return NULL;
return buf;
#endif
}
测试代码:
#include "osal.h"
#include "tn_test.h"
#include "app_common.h"
void SystemFunTest(void)
{
//test function: _ltoa
unsigned long tn_val = 0x34235678;
unsigned char buf[20];
_ltoa(tn_val, buf, 10);
_ltoa(tn_val, buf, 16);
}