Length of a UTF-8 byte sequence Determine the length of a UTF-8 byte sequence given its first byte. The following table shows which ranges map to each possible length:

  Range    Length
---------  ------
0x00-0x7F    1
0xC2-0xDF    2
0xE0-0xEF    3
0xF0-0xF4    4


Notes on gaps in the table: 0x80-0xBF are continuation bytes, 0xC0-0xC1 would start an overlong, invalid sequence, 0xF5-0xFF would result in a codepoint beyond the Unicode maximum.

Write a program or function that takes the first byte of a UTF-8 byte sequence as input and outputs or returns the length of the sequence. I/O is flexible. For example, the input can be a number, an 8-bit character or a one-character string. You can assume that the first byte is part of a valid sequence and falls into one of the ranges above.

This is code golf. The shortest answer in bytes wins.

Test cases

0x00 =&gt; 1
0x41 =&gt; 1
0x7F =&gt; 1
0xC2 =&gt; 2
0xDF =&gt; 2
0xE0 =&gt; 3
0xEF =&gt; 3
0xF0 =&gt; 4
0xF4 =&gt; 4
Z80Golf, 19 14 bytes

00000000: 2f6f 3e10 37ed 6a3d 30fb ee07 c03c       /o&gt;.7.j=0....&lt;


Try it online!

-5 bytes thanks to @Bubbler

Example with input 0x41-Try it online!
Assembly

Example with input 0xC2-Try it online!

Example with input 0xE0-Try it online!

Example with input 0xF4-Try it online!

Assembly:

;input: register a
;output: register a
byte_count:&#9;&#9;&#9;;calculate 7^(log2(255^a))||1
&#9;cpl&#9;&#9;&#9;;xor 255
&#9;ld l,a
&#9;log2:
&#9;&#9;ld&#9;a,16
&#9;&#9;scf
&#9;log2loop:
&#9;&#9;adc&#9;hl,hl
&#9;&#9;dec&#9;a
&#9;&#9;jr&#9;nc,log2loop
&#9;xor 7
&#9;ret nz
&#9;inc a


Try it online!