2

In my current program, I need to format an integer into an ASCII character. This will work with sprint() or snprintf().

Is there any alternative to sprintf() or snprintf() to format the data?

Thanks, Pavan.

3 Answers3

3
char ch = (char)(i + (int)'0'); /* Where i is an integer */

This works for 0 to 9

Gopi
  • 19,784
  • 4
  • 24
  • 36
1

You could use any of *printf() functions, such as printf, s(n)printf, fprintf etc. *print**f** means "formatted printing". You might also try printf("%c",(char)65) but this might not help you very much. Built-in functions are in most cases faster than "self-written".

ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

The original question didn't make it clear that the input is a string containing an integer in decimal form, but reading the comments leads to a much lighter weight solution than sprintf

(char)(atoi(decimal_str))

Casting to char ensures the integer will be limited to 8 bits with the code of the same value. atoi converts a string of digits into an integer

sirlark
  • 2,187
  • 2
  • 18
  • 28
  • Posted as an answer for future readers, so they don't have to dig through comments – sirlark Jan 19 '15 at 17:49
  • In what library/include file did you find this function `chr()`? It's not in any of the standard libraries. See also http://stackoverflow.com/questions/6405137/asc-and-chr-equivalent-in-c-c. – Jongware Jan 19 '15 at 18:33
  • Yes sorry, it's not standard. Confusion between turbo c and turbo pascal, in my foggy old memory. I've amended accordingly – sirlark Jan 19 '15 at 19:18