Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Convert an integer value to ASCII character

692 views
Skip to first unread message

Xianwen Chen

unread,
Feb 22, 2011, 10:31:14 PM2/22/11
to
Hi there,

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.

ebayc...@yahoo.com

unread,
Feb 23, 2011, 3:16:03 AM2/23/11
to
the ASCII code is the character. There is no need for conversion.
To obtain a space character, do either

myspace = ' ';
or
myspace = 0x20; /* ASCII value */

news

unread,
Feb 24, 2011, 2:05:08 PM2/24/11
to
On 23.2.2011 5:31, Xianwen Chen wrote:
> Hi there,
>
> 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?
>

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.

Jens Schmidt

unread,
Mar 1, 2011, 5:36:14 AM3/1/11
to
news wrote:

> 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

Jeremy Hall

unread,
Mar 3, 2011, 6:07:53 PM3/3/11
to
Hi,

> 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

0 new messages