bitwise operators
string length
programming
C language
code optimization

Strlen of MAX 16 chars string using bitwise operators

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

If a C string is guaranteed to be at most 16 characters long, you can compute its length with more than a simple byte-by-byte loop. One common low-level trick is to inspect several bytes at once and use bitwise operations to detect whether any byte in a machine word is zero, which can reduce branchy per-character checks.

The Core Problem

A C string ends at the first '\0' byte. Ordinary strlen walks one byte at a time until it finds that zero. For very short strings, that is often already fast enough. But if the goal is specifically to explore a bitwise technique, the usual trick is "detect whether a word contains a zero byte."

The Zero-Byte Detection Trick

For an unsigned machine word x, a classic test for whether any byte is zero is:

c
((x - 0x0101010101010101ULL) & ~x & 0x8080808080808080ULL)

If the result is nonzero, at least one byte in the 64-bit word was zero.

You do not need to memorize the constant pattern to use it, but the important point is that the expression uses bitwise properties to detect null bytes in parallel across all bytes of the word.

A Safe 16-Byte Example

Because direct unaligned word reads can be unsafe or undefined on some systems, a cautious implementation can use memcpy into local 64-bit variables.

c
1#include <stdint.h>
2#include <stdio.h>
3#include <string.h>
4
5static int has_zero_byte(uint64_t x) {
6    return ((x - 0x0101010101010101ULL) &
7            ~x &
8            0x8080808080808080ULL) != 0;
9}
10
11size_t strlen_max16(const char *s) {
12    uint64_t first = 0;
13    uint64_t second = 0;
14
15    memcpy(&first, s, 8);
16    if (has_zero_byte(first)) {
17        for (size_t i = 0; i < 8; ++i) {
18            if (s[i] == '\0') return i;
19        }
20    }
21
22    memcpy(&second, s + 8, 8);
23    for (size_t i = 8; i < 16; ++i) {
24        if (s[i] == '\0') return i;
25    }
26
27    return 16;
28}
29
30int main(void) {
31    char text[17] = "hello";
32    printf("%zu\n", strlen_max16(text));
33    return 0;
34}

The bitwise part helps locate which 8-byte block contains a zero. The small follow-up loop then finds the exact byte index within that block.

Why This Is a Two-Stage Technique

The word-level test is very good at answering:

"Does this block contain a null byte?"

It does not directly tell you the exact byte position in a friendly portable way, so the common approach is:

  1. test one block at a time
  2. once a block is known to contain zero, scan that small block precisely

For a max-16-character string, that means at most two block checks and one tiny fallback scan.

Is It Worth It

In real code, the standard library strlen is usually the right answer because compilers and libc implementations are already highly tuned. This bitwise technique is mostly useful when:

  • learning low-level string tricks
  • implementing specialized routines
  • understanding how optimized strlen implementations work internally

So the technique is interesting and valid, but it should not replace ordinary strlen casually.

Common Pitfalls

The biggest pitfall is reading past valid memory. Even if the string length is at most 16, the memory region must still be safe to inspect in the chunks your code reads.

Another common mistake is assuming this bitwise approach is automatically faster in every case. Modern strlen is already heavily optimized, and a custom routine may be slower or less portable.

Developers also sometimes forget signedness and alignment details. Low-level bit tricks should use unsigned integer types and careful memory access patterns.

Summary

  • A max-16-character C string can be checked in small word-sized blocks instead of byte by byte.
  • A classic bitwise expression can detect whether a 64-bit block contains any zero byte.
  • A practical implementation uses block detection first, then a tiny exact scan.
  • This is mainly useful for low-level optimization study, not as a casual replacement for standard strlen.
  • Be careful with memory safety, alignment, and portability when applying bitwise string tricks.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.