storing integers as characters

Apr 2, 2011 at 1:06am
so i am generating a random number and i want to store that random number as the character of itself... i don't know how to do this.

1
2
3
char t;
(unsigned (time(NULL)));
t = rand()%9;


i know this is wrong because the number between 1-9 is getting converted into the ascii character i just dont know how to prevent this? help.... sorry if this doesn't make any sense!!
Apr 2, 2011 at 1:07am
t=rand()%9+'0';
Apr 2, 2011 at 1:14am
that works to perfection but i have absolutely no idea why? can you explain? if not thank you for the solution!
Apr 2, 2011 at 1:27am
Since the number is stored at the ascii value internally, you can simply "add" the value of '0'. Hence if you rand()%9 returns 0, you will get 0+'0', which would give you character '0'. The other numbers follow sequentially, so '0'+1 == '1', etc.
Apr 2, 2011 at 1:48am
'0'  ==  48  ==  48 + 0  ==  '0' + 0
'1'  ==  49  ==  48 + 1  ==  '0' + 1
'2'  ==  50  ==  48 + 2  ==  '0' + 2
...
'8'  ==  56  ==  48 + 8  ==  '0' + 8
'9'  ==  57  ==  48 + 9  ==  '0' + 9


Because the ascii values for the digits are in order you can derive the equation
char_digit = '0' + int_digit
Topic archived. No new replies allowed.