CodeBlanks Logo Icon CodeBlanks

ASCII and UTF-8

Learn the difference between ASCII and UTF-8.

ASCII and UTF-8

ASCII is a 7-bit table from 0-127; each letter is one byte. UTF-8 is Unicode's variable-length encoding: ASCII characters are one byte, non-Latin characters are 2-4 bytes.

In C, char is one byte and strlen counts bytes; so strlen("Merhaba") returns 7 while strlen("çağ") returns 5 ('ç' and 'ğ' are two bytes each). The ASCII value of 'A' is 65. The difference between byte count and character count is the essence of UTF-8.

Counting bytes

To print the ASCII value of 'A' you write printf("%d", 'A');; this prints 65. strlen gives the byte count of a string.

Example: strlen("Merhaba") returns 7; 'M', 'e', 'r', 'h', 'a', 'b', 'a' are seven bytes. For a pure ASCII string the byte count equals the character count. This fact is the basis of UTF-8 handling: you first get the byte count, then decode characters.

Practice ASCII value and byte count

Print the ASCII value of 'A' with printf("ASCII: %d\n", 'A');. Print the byte count of the string with printf("bayt: %zu\n", strlen("Merhaba"));. Don't forget <string.h>.

Starter code

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

// Print ASCII value of 'A' with %d
// Print byte count of "Merhaba" with strlen

int main(void) {
    return 0;
}

Sample solution

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

int main(void) {
    printf("ASCII: %d\n", 'A');
    printf("bayt: %zu\n", strlen("Merhaba"));
    return 0;
}

Expected output

ASCII: 65
bayt: 7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many bytes is the letter 'ü' in UTF-8?

  • 2 Correct answer
  • 1
  • 3
  • 4

Explanation: 'ü' is a non-Latin letter, so it is 2 bytes in UTF-8.

2 Find the string length

Question
int n = strlen("____");
Answer
int n = strlen("Merhaba");

Explanation: strlen("Merhaba") returns 7.

3 Match the concepts

Term Meaning
ASCII 7-bit 0-127
UTF-8 Variable length
char Single byte
strlen Counts bytes

All lessons in Advanced