0

I would like to add an int value in a char array. meaning if I have a 1, I would like to represent it like '1'.

I have seen an equation to do this before to get the ASCII code of it. am working with a limited compiler for C so I don't have the luxury to use functions like sprintf() or others. it has to be in the form of an equation that I must implement. Can anybody help me with that.

example of what I'd like to do

char array[2];
char array[0] = 1 * (equation);

and then array[0] should have the value '1'.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3567826
  • 19
  • 1
  • 4

2 Answers2

3

If you're working with values in range 0-9, you can use

array[0] = 1 + '0';

This will give you the char representation ('1')of int values (1).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • when I do this it prints out a '1' and then some strange characters next to it – user3567826 Apr 21 '15 at 21:40
  • @user3567826 you need to null terminate the array to use it as a string. Try adding `array[1] = 0;` after `array[0]` and check. :-) – Sourav Ghosh Apr 21 '15 at 21:42
  • seems to be working great! but how can I make it support ints larger than 9? – user3567826 Apr 21 '15 at 21:45
  • 1
    @user3567826: You can't; an integer larger than 9 won't fit in a single character if you're using decimal. If you use hexadecimal, you can store values from 10 to 15 as `'A'` through `'F'`. Of course you can store the value `10` as the two-character sequence `'1', '0'` -- but that's not what you asked for in your question. – Keith Thompson Apr 21 '15 at 22:00
0

One way is to add ASCII value of 0 to the already present number.

Suppose int t=8; then we can convert t to char as follows

int t=8;

char s= t + 48; //ASCII value of '0'

So your equation should be

char s= integer + 48 ;

SRIDHARAN
  • 1,196
  • 1
  • 15
  • 35