54 lines
1.3 KiB
C
54 lines
1.3 KiB
C
|
#include "itoa.h"
|
||
|
|
||
|
/*
|
||
|
* The heapless_itoa function is copied from the shellmatta project.
|
||
|
*/
|
||
|
|
||
|
/**
|
||
|
* @brief itoa like function to convert int to an ascii string
|
||
|
* @warning you have to provide a large enough buffer
|
||
|
* @param[in] value
|
||
|
* @param[in,out] buffer
|
||
|
* @param[in] base
|
||
|
* @return number of bytes in string
|
||
|
*/
|
||
|
uint32_t heapless_itoa(int32_t value, char *buffer, uint32_t base)
|
||
|
{
|
||
|
char tempBuffer[34u];
|
||
|
uint32_t i;
|
||
|
uint32_t bufferIdx = 0u;
|
||
|
int8_t digitValue;
|
||
|
|
||
|
/** -# check the base for plausibility */
|
||
|
if((base >= 2) && (base <= 16))
|
||
|
{
|
||
|
/** -# check for sign */
|
||
|
if(value < 0)
|
||
|
{
|
||
|
value = value * (-1);
|
||
|
buffer[0u] = '-';
|
||
|
bufferIdx += 1u;
|
||
|
}
|
||
|
|
||
|
/** -# loop through all digits in reverse order */
|
||
|
i = 0u;
|
||
|
do
|
||
|
{
|
||
|
digitValue = (int8_t) (value % base);
|
||
|
tempBuffer[i] = (digitValue < 10) ? ('0' + digitValue) : ('A' + (digitValue - 10));
|
||
|
value /= base;
|
||
|
i ++;
|
||
|
}while(value > 0);
|
||
|
|
||
|
/** -# store the string in the correct order onto the buffer */
|
||
|
while(i > 0u)
|
||
|
{
|
||
|
buffer[bufferIdx] = tempBuffer[i - 1u];
|
||
|
i --;
|
||
|
bufferIdx ++;
|
||
|
}
|
||
|
}
|
||
|
return bufferIdx;
|
||
|
}
|
||
|
|