I wish to display the contents of a variable, probably an unsigned integer, on an lcd display driven from the 8051. I have written software to accept an array of characters and write these, so the ideal would be to creat a similat array from the variable. I have tried the basic ways I know of, sprintf (char_array, "%d", integer_value); (very low tech) but dosent work. Any pointers would be greatfully recieved, Thank you, Tim
sprintf() really should work for you, but you have not provided enough context for us to determine why it doesn't. On the other hand, if you would only be using sprintf() for integer to ASCII conversion, you could do the conversion with less code overhead by using a function like: void UlToStr(char *s, unsigned long bin, unsigned char n); This is a function that stores a NUL-terminated string, in n + 1 (plus 1 for the NUL string terminator) successive elements of the array whose first element has the address s, by converting bin to n decimal characters. The function stores leading zeroes if necessary. If the leading zeroes are undesireable, you can replace them with spaces or start outputting at the first nonzero character.
void UlToStr(char *s, unsigned long bin, unsigned char n) { s += n; *s = '\0'; while (n--) { *--s = (bin % 10) + '0'; bin /= 10; } }
Dan, Thank you very much for your help. Thats fantastic! Tim
If you are interested in a faster radix conversion, see here: http://www.programmersheaven.com/zone5/cat27/32144.htm A general purpose radix conversion function is provided as a specific example. The algorithm used is successive division of the value by the radix - same as algorithm posted by Dan. However, this implementation should prove to be much faster than using just C.