Code Tricks: Printing fancy characters in C

Sometimes in output we might want to use something like the Greek character π. Printing the extended characters can be quite challenging in C. Although many systems don’t support the extended character set, it can be achieved using UTF-8 character encoding. It is able to represent any character in the Unicode standard, yet it is backwards compatible with ASCII. UTF-8 encodes each character (code point) in 1 to 4 octets (8-bit bytes), with the single octet encoding used only for the 128 US-ASCII characters.

For instance in Xcode, we can print characters to stdout using:

printf(“%c%c\n”, 0xcf, 0x80);

This prints the character equivalent to the UTF-8 code cf80, which is π. The next example prints the phrase πr²:

printf(“%c%cr%c%c\n”, 0xcf, 0x80, 0xc2, 0xb2);

Here are some of the more commonly used codes:

0xcf, 0x80       π
0xc2, 0xb0       °
0xc2, 0xb2       ²
0xc2, 0xb3       ³
0xc2, 0xbd       ½

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.