This is a custom function to convert a number to the ASCII representation
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| void ULongToStr(unsigned long value, char *str,char trailing_zero,char digits)
{
char first_non_zero=1;
str+=(digits-1); // move the pointer to the last char of the array
while (digits!=0) // execute the loop for the times defined in digits variable
{ if (value==0) // if the remaining number is 0 then just add '0' to speed up the conversion
{ *str='0';
str--; // move to the previous char of the array
}
else
{
*str = (char) ((value%10)+48); // find the digit value using modulo and assign the ASCII representation
str--; // move to the previous char of the array
value= value/10; // divide input input number by 10 for next loop
}
digits--; // used as a counter to detect when we have reached the first char of the array
}
// at this point the array pointer is at the address &array[0]-1
if (trailing_zero==0) // if parameter is set for no trailing zeroes
{
while(first_non_zero==1) // if the first digit of the number is not found
{ str++; // move to next array character
if (*str=='0') *str=0; // if digit value is ADCII 0 then replace with null (user selectable)
else first_non_zero=0; // else set the flag that the first digit of the number was found
}
}
} |
to call it
ULongToStr(value, my_char_array, trailing_zero, digits);
where
value is an unsigned variable but can be modified to use a signed variable and you have to take care of the sign for negative numbers
my_char_array is a pointer to the first char of the array (the same as &my_char_array[0])
trailing_zero can be 0 so that trailing zeroes are replaced with null or 1 to leave them as 0
digits is the number of digits that will be converted starting from the last digit of the provided number, if you use 5 and the number is 123567890 then the array result will be 67890
the routine takes about 12200 clocks (in AVR) for 10 characters and is reduced about 1000 cycles for each lower character count (9,8,7 etc) while sprintf takes about 2700 clock but at the same time this routine uses about 1500 bytes less space than sprintf.
I would be happy to hear any suggestions to make the function more efficient or an alternative custom function
Alex
EDIT: I have made a small modification in line 6 to speed up the conversion when the number of digits of the input number are less that the specified result digits