0

How to cast char=2 to char="2" ?

i need it to send via uart, but when im trying to send char as 2 i get nothing, but when i send as "2" i get 2

The point is, i have

int s=2;

and i need to write it to char as "2" not 2. i tried a few ways but always failure. when char = 2 message in terminal is just empty, when char is signed as "2" it works fine. When i tries to convert int to char , char was always signed as 2, i can't just send int via uart becouse block sending function needs pointer.

3 Answers3

1

you can use itoa() to convert an integer to a char.

http://www.jb.man.ac.uk/~slowe/cpp/itoa.html

Gung Foo
  • 13,392
  • 5
  • 31
  • 39
  • tried but compilator said that there is no itoa function in stdlib.h this app is not writen for pc. – user2304765 May 18 '13 at 18:51
  • There is. So You probably tried to use it with invalid parameters. http://www.cplusplus.com/reference/cstdlib/itoa/ –  May 18 '13 at 18:54
  • undefined reference to 'itoa' , #include – user2304765 May 18 '13 at 18:59
  • I looked it up. Itoa is not defined in ANSI C, but is supported by some compilers. If it doesn't work, write it for Yourself like it is on the linked page –  May 18 '13 at 18:59
  • how can i write it for my self if i can't make this work, sry im a little bit newmbie in C. – user2304765 May 18 '13 at 19:05
  • Look into sprintf/snprintf as suggested [here](http://stackoverflow.com/questions/8770408/convert-int-to-char-in-standard-c-without-itoa) – Nigel Harper May 18 '13 at 19:11
  • it works, thanks, but in other case i have other data for ex. "d728u32hbdua239" in char how to convert it to string to char*="d728u32hbdua239" , this data is pure binary data – user2304765 May 18 '13 at 19:19
  • Probably time for another question about this case – Nigel Harper May 18 '13 at 19:34
0

If you need only one char at once, You can use the following too:

char s =2;
s+='0'; 
0

What is the function head for the the call you use to send via the uart? Can you give us any more information about what the device is?

You can fix how you send on one end, or you can change how you read on the other end. Presumably you can read data as integers, or cast it, so not everything has to be sent via strings, and this whole conversion problem would go away.

All this being said, you can convert 0-9 from integer into ascii code by adding a constant 48, but I don't think that's really what you're going for.

Macattack
  • 1,917
  • 10
  • 15