Author Topic: convert Int to Char C++  (Read 4864 times)

0 Members and 1 Guest are viewing this topic.

Offline RatfinkTopic starter

  • Jr. Member
  • **
  • Posts: 27
  • Helpful? 0
convert Int to Char C++
« 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

Offline Somchaya

  • Robot Overlord
  • ****
  • Posts: 180
  • Helpful? 0
  • You know it's cute!
Re: convert Int to Char C++
« Reply #1 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
« Last Edit: April 03, 2007, 02:22:42 PM by Somchaya »
Somchaya - Back after a year of misc things
http://whisker.scribblewiki.com

Offline RatfinkTopic starter

  • Jr. Member
  • **
  • Posts: 27
  • Helpful? 0
Re: convert Int to Char C++
« Reply #2 on: April 03, 2007, 02:13:36 PM »
how do i get the next value 9? doing 2893%100 gives 93

Offline Somchaya

  • Robot Overlord
  • ****
  • Posts: 180
  • Helpful? 0
  • You know it's cute!
Re: convert Int to Char C++
« Reply #3 on: April 03, 2007, 02:22:24 PM »
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.
« Last Edit: April 03, 2007, 02:27:22 PM by Somchaya »
Somchaya - Back after a year of misc things
http://whisker.scribblewiki.com

Offline RatfinkTopic starter

  • Jr. Member
  • **
  • Posts: 27
  • Helpful? 0
Re: convert Int to Char C++
« Reply #4 on: April 03, 2007, 02:40:30 PM »
argh i forgot that the decimal is ignored thanks for this!

 


Get Your Ad Here