Software > Software

convert Int to Char C++

(1/1)

Ratfink:
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

Somchaya:
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

Ratfink:
how do i get the next value 9? doing 2893%100 gives 93

Somchaya:
Oh, I guess I should do a loop then to show you:

char values[4];
int num = 2893;

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

This way, values[0] = '3', values[1] = '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.

Ratfink:
argh i forgot that the decimal is ignored thanks for this!

Navigation

[0] Message Index

Go to full version