contributed by < Eric Lin >
The technique used to detect \0
character by strlen in IOS:
The same techique can be found in string/strlen.c:
I am curious about why this code can detect NULL byte.
First, simplify the code to detecting whether one byte data is NULL or not:
Convert it according to De Morgan's laws:
Switch the first two parameters' position:
Now, if X = 0
:
Other X != 0
conditions:
~(0x01 | 0xFFFFFFFFF) => 0x0 & 0x80 => 0
X = 0
, the outcome from DETECTNULL(X)
will be 0x80
.X != 0
, the outcome will be 0
.This detecting NULL implementation is more efficent than compares one byte at the time like this:
source: [你所不知道的 C 語言:數值系統](https://hackmd.io/@sysprog/c-numerics#算術完全可用數位邏輯實作