Society of Robots - Robot Forum

Software => Software => Topic started by: Ratfink on April 03, 2007, 02:05:16 PM

Title: convert Int to Char C++
Post by: Ratfink on April 03, 2007, 02:05:16 PM
Im using F2812 EzDSP processor and i can't use stdlib.h or the ioctl function for this so any help is appreciated

Problem is as follows i have a 12 bit integer e.g. 2893
i wish to seperate out each integer so i get 2 8 9 3 and convert each one to its ASCII representation e.g. 2 is 50 8 is 56 etc..

Any ideas given will be appreciated
Title: Re: convert Int to Char C++
Post by: Somchaya on April 03, 2007, 02:08:39 PM
What you could do is to split the digits by dividing/mod by 10, and then add the relevant ascii value to it.

For example:
int num = 2893
int ones = num % 10;
char ones_c = ones + '0'; // ones_c = '3'

You could imagine doing the same for the other digits, although putting it all into a loop would probably make more sense.

Edit: had an error in the code
Title: Re: convert Int to Char C++
Post by: Ratfink on April 03, 2007, 02:13:36 PM
how do i get the next value 9? doing 2893%100 gives 93
Title: Re: convert Int to Char C++
Post by: Somchaya on April 03, 2007, 02:22:24 PM
Oh, I guess I should do a loop then to show you:

char values;
int num = 2893;

for (i = 0; i < 4; i++) {
int ones = num % 10;
num = num / 10;
values[i ] = ones + '0';
}

This way, values = '3', values = '9', and so on.

If you wanted them in the right order, just change values[i ] to values[3 - i]

What happens here is that the number is repeatedly divided by 10, so the ones digit yields the number you want each iteration.

Edit: [i ] didn't show up correctly, changed variable names so it's a little clearer.
Title: Re: convert Int to Char C++
Post by: Ratfink on April 03, 2007, 02:40:30 PM
argh i forgot that the decimal is ignored thanks for this!