Characters and text

A char is a one-byte number. Which character each number means is fixed by a table: ASCII for the first 128 values. 'A' is 65, 'a' is 97, '0' is 48, a space is 32 and the newline '\n' is 10.

Letters are numbers

#include <stdio.h>

int main(void) {
    char c = 'g';
    printf("'%c' is %d\n", c, c);
    printf("position in the alphabet: %d\n", c - 'a');
    printf("uppercase: %c\n", c - 32);
    char d = '7';
    printf("digit value: %d\n", d - '0');
    return 0;
}
Open in compiler

Because letters are in order, you can do arithmetic on them:

  • c - 'a' is a letter's position in the alphabet (0 for a);
  • c - 32 turns a lowercase ASCII letter into uppercase ('a' - 'A' is 32);
  • d - '0' turns a digit character into its number: '7' - '0' is 7.

This is how toupper, atoi and the Caesar cipher work.

Beyond ASCII: Unicode and UTF-8

#include <stdio.h>
#include <string.h>

int main(void) {
    char word[] = "অ";
    printf("bytes: %zu\n", strlen(word));
    for (int i = 0; word[i] != '\0'; i++) printf("%d ", (unsigned char)word[i]);
    printf("\n");
    return 0;
}
Open in compiler

ASCII has no Bangla letters, no accents and no emoji. Unicode gives every character in every script a number (a code point): অ is U+0985. UTF-8 stores those numbers in 1 to 4 bytes: ASCII characters keep their single byte, and others use 2, 3 or 4. So strlen counts bytes, not letters: "অ" has length 3. Watch the array in the visualizer: three bytes for one letter.

CharacterCode pointUTF-8 bytes
AU+00411
éU+00E92
অU+09853
😀U+1F6004

Quick check

1. What is 'C' - 'A'?
2. What does '9' - '0' give?
3. How many bytes does UTF-8 use for the Bangla letter অ?

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.