I'm trying to convert an integer valune to ASCII character. I have
found that I can print an integer value to a character by
printf("%c", intA);
What I am looking for is something like
charA = somefunction(intA)
Some hints, please?
Regards,
Xianwen
--
comp.lang.c.moderated - moderation address: cl...@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
myspace = ' ';
or
myspace = 0x20; /* ASCII value */
int n = 20 ;
unsigned char c = (char) n & 0xFF;
That used to work when I last checked. "& 0xFF" is not mandatory but
still good thing to to.
> int n = 20 ;
> unsigned char c = (char) n & 0xFF;
>
> That used to work when I last checked. "& 0xFF" is not mandatory but
> still good thing to to.
This could never have worked. ASCII is a 7-bit character set, so you
shoud have masked with 0x7F. Luckily most programs don't do that, so
users are not restricted to ASCII.
Also, this is quite complicated. What happens here is:
int n is converted to char
char is implicitly converted to int
the int is and-ed with another int
the result is converted to unsigned char
Consideration of the generated code for various optimization levels
and character sizes from 8 to 64 bits are left to the reader. :-)
--
Greetings,
Jens Schmidt
> Consideration of the generated code for various optimization levels
> and character sizes from 8 to 64 bits are left to the reader. :-)
Try gcc!
No code at all is emitted for the above sequence, for 8 bit chars
anyway.
int n = 20 ;
unsigned char c = (char) n & 0xFF;
printf("%c\n", c);
gcc simply does a "push 20" followed by the printf stuff.
All that's needed is unsigned char c = (char)n;
The cast is only required to avoid warnings from the implicit
narrowing conversion.
Regards
Jeremy