Get length of multibyte UTF-8 sequence

c, utf-8

Solution

Just strip out all bytes which are no valid ascii, don't try to get cute and interpret bytes >127 at all. This works as long as you don't have any combining sequences with base character in ascii range. For those you would need to interpret the codepoints themselves.

Problem

I am parsing some UTF-8 text but am only interested in characters in the ASCII range, i.e., I can just skip multibyte sequences. I can easily detect the beginning of a sequence because the sign bit is set, so the `char` value is < 0. But how can I tell how many bytes are in the sequence so I can skip over it? I do not need to perform any validation, i.e., I can assume the input is valid UTF-8.

Original source