C UTF-8 in C

Intermediate
9 min read
Updated: Nov 2026
3 examples

What Is UTF-8 in C?

UTF-8 encodes each Unicode code point as 1 to 4 bytes. In C, a UTF-8 string is just a char array ending in \0, so functions like strlen() count bytes, not characters. You must treat the bytes as a variable-length encoding yourself.

Remember
code point range         bytes   byte pattern
U+0000  - U+007F        1       0xxxxxxx
U+0080  - U+07FF        2       110xxxxx 10xxxxxx
U+0800  - U+FFFF        3       1110xxxx 10xxxxxx 10xxxxxx
U+10000 - U+10FFFF      4       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

continuation bytes always look like 10xxxxxx
CharacterCode pointUTF-8 bytes
AU+004141 (1 byte)
éU+00E9C3 A9 (2 bytes)
€U+20ACE2 82 AC (3 bytes)
😀U+1F600F0 9F 98 80 (4 bytes)

How to Work with UTF-8 in C

Treat the string as bytes, use the lead byte to find sequence lengths, and skip continuation bytes when you count characters.

  1. Keep text in char arrays (or unsigned char when decoding) and end with \0.
  2. Use strlen() for the byte length, for buffers and memcpy().
  3. Count code points by counting bytes that are not continuation bytes: (b & 0xC0) != 0x80.
  4. Decode with the lead byte pattern to get the numeric code point.
  5. Never cut a string in the middle of a multi-byte sequence.
NeedUseCaveat
Byte lengthstrlen()Not the character count
Code point countSkip 10xxxxxx bytesNot the same as visible glyphs
Simple ASCII testsctype.h functionsOnly valid for single bytes
Full Unicode textA library such as ICU or utf8procNormalization, case, width

Pseudocode

Pseudocode
for each byte b in the string:
    if (b AND 0xC0) != 0x80:     // not a continuation byte
        code_point_count = code_point_count + 1

lead byte tells the length:
    0xxxxxxx -> 1   110xxxxx -> 2   1110xxxx -> 3   11110xxx -> 4

Cheat Sheet

Rules of thumb for UTF-8 strings in C.

TopicDetail
strlen(s)Bytes before \0
Continuation byte(b & 0xC0) == 0x80
ASCII compatibilityBytes below 0x80 are plain ASCII
\0 byteNever appears inside a valid sequence
wchar_t16 bits on Windows, 32 bits on Linux and macOS
OutputTerminal and locale must also expect UTF-8

Worked Walkthrough — The String héllo

The literal "h\xC3\xA9llo" is the text “héllo” written with explicit bytes so it does not depend on your source file encoding.

Calculation
byte index:  0    1    2    3    4    5
byte value:  68   C3   A9   6C   6C   6F
meaning:     h    [  e-acute ]   l    l    o

strlen            -> 6 bytes
continuation bytes (10xxxxxx) -> only A9
code points       -> 6 - 1 = 5

Slicing at byte 2 would cut e-acute in half and leave invalid UTF-8.

C Examples

Compile with gcc file.c -std=c11 -o out. The examples use explicit hex escapes so they behave the same on any source encoding. For wide strings see wchar.h.

Example 1 — Count Bytes and Code Points

Compare strlen() with a loop that skips continuation bytes.

C
#include <stddef.h>
      #include <stdio.h>
      #include <string.h>
      
      static size_t utf8_count(const char *s) {
          size_t count = 0;
          for (; *s != '\0'; s++) {
              if (((unsigned char)*s & 0xC0) != 0x80) {
                  count++;
              }
          }
          return count;
      }
      
      int main(void) {
          const char *text = "h\xC3\xA9llo";   /* "h" + e-acute + "llo" */
      
          printf("bytes       = %zu\n", strlen(text));
          printf("code points = %zu\n", utf8_count(text));
          return 0;
      }

How It Works

  1. Explicit bytes. \xC3\xA9 is the two-byte UTF-8 form of é.
  2. strlen. It counts every byte, so the answer is 6.
  3. Skip continuation bytes. 0xA9 matches 10xxxxxx and is not counted.
  4. Cast to unsigned char. Avoids sign-extension on platforms where char is signed.

Example 2 — Decode 1 to 3 Byte Sequences

Read the lead byte, then combine the payload bits into a code point number.

C
#include <stdio.h>
      
      /* Decodes one sequence. Returns bytes used, or -1 on a bad lead byte.
         Does not validate continuation bytes; real code must. */
      static int utf8_decode(const unsigned char *s, unsigned long *cp) {
          if (s[0] < 0x80) {
              *cp = s[0];
              return 1;
          }
          if ((s[0] & 0xE0) == 0xC0) {
              *cp = ((unsigned long)(s[0] & 0x1F) << 6) | (s[1] & 0x3F);
              return 2;
          }
          if ((s[0] & 0xF0) == 0xE0) {
              *cp = ((unsigned long)(s[0] & 0x0F) << 12)
                  | ((unsigned long)(s[1] & 0x3F) << 6)
                  | (s[2] & 0x3F);
              return 3;
          }
          return -1;
      }
      
      int main(void) {
          const unsigned char text[] = "A\xC3\xA9\xE2\x82\xAC";   /* A, e-acute, euro */
          const unsigned char *p = text;
      
          while (*p != '\0') {
              unsigned long cp;
              int n = utf8_decode(p, &cp);
              if (n < 0) {
                  break;
              }
              printf("U+%04lX (%d byte%s)\n", cp, n, n == 1 ? "" : "s");
              p += n;
          }
          return 0;
      }

How It Works

  1. 1 byte. Values below 0x80 are ASCII and map directly.
  2. 2 bytes. C3 A9 keeps 5 bits from the lead and 6 from the next: 0xE9.
  3. 3 bytes. E2 82 AC gives 0x20AC, the euro sign.
  4. Advance by length. p += n jumps to the next sequence.

Example 3 — Cut a String Without Splitting a Character

When you must truncate to a byte limit, back up past any continuation bytes.

C
#include <stdio.h>
      #include <string.h>
      
      /* Largest length <= max that does not end inside a sequence. */
      static size_t safe_len(const char *s, size_t max) {
          size_t len = strlen(s);
          if (len <= max) {
              return len;
          }
          while (max > 0 && ((unsigned char)s[max] & 0xC0) == 0x80) {
              max--;
          }
          return max;
      }
      
      int main(void) {
          const char *text = "h\xC3\xA9llo";   /* 6 bytes */
      
          printf("limit 2 -> %zu bytes\n", safe_len(text, 2));
          printf("limit 3 -> %zu bytes\n", safe_len(text, 3));
          printf("limit 9 -> %zu bytes\n", safe_len(text, 9));
          return 0;
      }

How It Works

  1. Limit 2. Byte 2 is A9, a continuation byte, so the cut moves back to 1 (just h).
  2. Limit 3. Byte 3 is l, a lead byte, so 3 bytes (h and the full é) are safe.
  3. Limit 9. The string is shorter than the limit, so the whole 6 bytes are kept.
  4. Idea. Check the byte after the cut, and back up while it is a continuation byte.

Edge Cases & Pitfalls

UTF-8 bugs usually come from treating bytes as characters.

strlen

strlen is not a character count

It returns bytes. A 5-letter word with one accented letter has length 6.

ctype

ctype.h on multibyte text

isalpha, toupper, and friends work on single bytes only. They do not understand multi-byte letters.

slice

Cutting mid-character

Copying a fixed number of bytes can leave half a sequence, which shows as garbage or breaks parsers.

invalid

Invalid or overlong input

Decoders must reject stray continuation bytes, truncated sequences, and overlong forms from untrusted input.

wchar

wchar_t is not UTF-8

Its size and encoding depend on the platform. Convert at the edges with mbstowcs or a library.

console

Terminal and locale

A Windows console or a non-UTF-8 locale can print correct bytes as garbage. Check the code page and locale.

Performance Notes

TaskCostNotes
Byte lengthO(n)strlen scans for \0
Count code pointsO(n)One pass, no allocation
Random access to nth characterO(n)Variable width means no direct index

Because characters are variable width, finding the nth code point needs a scan. Keep byte offsets when you need fast random access, and convert only when an API requires fixed-width characters.

Key Takeaways

  • Encoding: UTF-8 uses 1 to 4 bytes per code point.
  • Length: strlen returns bytes, not characters.
  • Counting: skip bytes of the form 10xxxxxx.
  • Safety: validate input and never split a sequence.

One line: in C, UTF-8 is just bytes; you provide the character logic.

Frequently Asked Questions

Yes in practice. A UTF-8 string is a normal null-terminated char array. The standard library does not interpret the multi-byte structure for you.
strlen counts bytes up to the null terminator. Letters like é use two bytes, so the byte count is larger than the character count.
Count the bytes that are not continuation bytes, meaning those where (byte & 0xC0) != 0x80. This counts code points.
No. wchar_t is a fixed-width type whose size and encoding vary by platform, usually UTF-16 on Windows and UTF-32 on Linux and macOS.
Only for ASCII bytes. They operate on single bytes and will not handle multi-byte letters correctly.
A library such as ICU or utf8proc for normalization, case mapping, and grapheme handling. The C standard library covers only basics.

Next: C Standard Library

Browse the standard headers and what each one provides.

C Library hub →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful