I’m trying to break down an integer with C on an 8-bit microcontroller (a PIC) into its ASCII equivalent characters.
For example:
convert 982 to ‘9’,’8′,’2′
Everything I’ve come up with so far seems pretty brute force. This is the main idea of what I’m basically doing right now:
if( (10 <= n) && (n < 100) ) {
// isolate and update the first order of magnitude
digit_0 = (n % 10);
// isolate and update the second order of magnitude
switch( n - (n % 10) ) {
case 0:
digit_1 = 0;
break;
case 10:
digit_1 = 1;
break;
…
And then I have another function to just add 0b00110000 (48decimal) to each of my digits.
I’ve been having trouble finding any C function to do this for me or doing it well myself.
Thanks in advance for any help!
To do it yourself you need to perform the operations which are demonstrated with the sample code below:
The
whileloop will chop out the digits from the integer in a given base and feed the digits in reverse order in an array. The innerif - elsehandles base more than 9, and places uppercase alphabets when a digit value is greater than 10. Theforloop reverses the string and gets the chopped number into string in forward order.You need to adjust the size of
x_strarray as per your max capability. Define a macro for it. Note the above code is only for unsigned integers. For signed integers you need to first check if it is below 0, then add a ‘-‘ sign inx_strand then print the magnitude ie. apply the above code with-x. This can also be done by checking the sign bit, by masking, but will make the process dependent on storage of integer.The
base_valis the base in which you want to interpret the numbers.