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'.

1

2 Answers 2

5

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).

Sign up to request clarification or add additional context in comments.

4 Comments

when I do this it prints out a '1' and then some strange characters next to it
@user3567826 you need to null terminate the array to use it as a string. Try adding array[1] = 0; after array[0] and check. :-)
seems to be working great! but how can I make it support ints larger than 9?
@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.
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 ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.