You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

x86-64最小指令长度strlen实现技术咨询

Analysis of Your x86-64 strlen Implementation

First, let's start with a critical observation: your current code has a logic bug that returns the wrong length, and fixing it also gives you an immediate size optimization.

The Bug & Quick Fix

Your final dec ecx instruction is incorrect. Let's walk through the math step by step:

  • You initialize ecx = -1 (0xFFFFFFFF) and al = 0.
  • repne scasb scans until it hits a null byte, decrementing ecx once for every non-null byte it encounters. For a string of length n, this means ecx ends up as -(n + 1) (since we scanned n non-null bytes, each decrementing ecx from its starting value of -1).
  • not ecx flips the bits of -(n+1), which gives you exactly n (the correct strlen result).
  • Adding dec ecx then subtracts 1, leaving you with n-1—which is wrong for all non-empty strings.

Removing the dec ecx fixes the bug and cuts your total instruction length from 11 bytes to 9 bytes:

xor eax,eax ; 2 bytes (sets al=0)
or ecx,-1   ; 3 bytes (sets ecx=-1)
repne scasb ; 2 bytes
not ecx     ; 2 bytes

Total: 9 bytes, with the correct strlen value stored in ecx.

Further Size Optimization

Is there a way to shrink this even more? Let's explore the options:

  • Setting ecx=-1: Your or ecx,-1 is the shortest possible way to do this (3 bytes). Alternatives like xor ecx,ecx; dec ecx cost 4 bytes total, which is longer.
  • Setting al=0: xor eax,eax is 2 bytes, same as mov al,0—no gain here.
  • 64-bit register usage: Using rcx instead of ecx would require or rcx,-1 (4 bytes), which adds a byte, so that's worse (especially since you noted the max length is Int32).

At 9 bytes, this is already extremely compact for a correct repne scasb-based strlen. I don't know of any valid x86-64 instruction sequences that can get this shorter while maintaining correctness for all valid input strings.

Potential Edge Cases & Caveats

Even with the bug fixed, keep these in mind for your use case:

  • Null-termination requirement: Like standard strlen, this relies entirely on the input string being null-terminated. If the string has no null byte, it will scan 4GB of memory (since ecx starts at -1, the maximum Int32 value) until ecx underflows to 0, which will cause invalid memory accesses or wrong results.
  • Register clobbering: This implementation modifies rax, rcx, and rdi. In code golf or demo scenarios, this is usually acceptable, but make sure your environment allows these registers to be overwritten.
  • Performance: While size-optimized, repne scasb isn't the fastest strlen implementation (especially for long strings), but that's irrelevant for code golf/demo use cases where size is the priority.

内容的提问来源于stack exchange,提问作者Kamil.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:59:05