Author Topic: Integer to string conversion  (Read 9686 times)

0 Members and 1 Guest are viewing this topic.

Offline wicketTopic starter

  • Contributor
  • Posts: 35
Integer to string conversion
« on: April 22, 2014, 08:57:50 am »
Hi,

is there a way to convert an integer to string (array of chars) in c? For example int x = 15 to char y[] = "15" ? I'm using MPLAB (xc8 compiler).
 

Offline andtfoot

  • Supporter
  • ****
  • Posts: 352
  • Country: au
Re: Integer to string conversion
« Reply #1 on: April 22, 2014, 10:01:27 am »
For a more manual method, you could try the following. I'm not much of a programer, so I wouldn't know the syntax to actually achieve it.
- Divide the number into individual digits (e.g. 157 is (1 x 100) + (5 x 10) + (7 x 1))
- For each number, add 48 to it. This gives the ASCII value of that number (e.g 1 + 48 = 49 = ASCII '1'  ...  5 + 48 = 53 = ASCII '5'  ...  7 + 48 = 55 = ASCII '7')

Not sure if then you can feed in the numerical ASCII value instead of a char to then print it.
 

Offline DmitryL

  • Regular Contributor
  • *
  • Posts: 242
  • Country: gb
Re: Integer to string conversion
« Reply #2 on: April 22, 2014, 10:10:58 am »
Hi,

is there a way to convert an integer to string (array of chars) in c? For example int x = 15 to char y[] = "15" ? I'm using MPLAB (xc8 compiler).

There are too many ways to skin this cat.
As already mentioned, you can use sprintf (heavy).
Also, if you don't want to use sprintf and division, you can try to convert your number to BCD and convert BCD nibbles to characters.
http://stackoverflow.com/questions/13247647/convert-integer-from-pure-binary-to-bcd
 

Offline Codemonkey

  • Regular Contributor
  • *
  • Posts: 235
  • Country: gb
Re: Integer to string conversion
« Reply #3 on: April 22, 2014, 10:11:44 am »
See if you have the itoa() function available in MPLAP. I don't use it so I've no idea.
 

Offline wicketTopic starter

  • Contributor
  • Posts: 35
Re: Integer to string conversion
« Reply #4 on: April 22, 2014, 11:36:33 am »
itoa() worked for me, thanks.
 

Offline icon

  • Regular Contributor
  • *
  • Posts: 246
Re: Integer to string conversion
« Reply #5 on: April 22, 2014, 07:21:50 pm »
Hi

(I know you've solved it but) Some useful info here:

https://www.eevblog.com/forum/microcontrollers/(pic)-converting-sfrgpr-values-to-strings/

Regards
John
 

Offline amwales

  • Regular Contributor
  • *
  • Posts: 80
  • Country: gb
Re: Integer to string conversion
« Reply #6 on: April 23, 2014, 10:36:29 pm »
RANT ON ---->

The xc8 library is appalling and the optimized code produced by the compiler is bad enough to make you hurl. Just take a look at the shit it kicks out if you write

*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;


<---- RANT OFF
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf