The glibc strlen implementation uses a bitwise trick to check multiple bytes at once for null characters (0x00). By treating 4 bytes as a 32-bit value, it subtracts a mask (lomagic) and applies bitwise operations to detect any zero byte via borrow propagation. This avoids slow byte-by-byte comparisons, improving performance on architectures where branching is expensive.
A Short Note on strlen
Still computing string lengths by checking each byte one by one for 0x00?
Apparently, glibc implements strlen like this: check, say, 4 bytes at once (32 bits) to see whether any of them is 0x00, and then search more carefully.
For example, with a 32-bit register, you can check 4 bytes in one go.
What is this? Because 0x00 - 0x01 creates a borrow, and the value after the borrow is 0xFF, which is the same as inverting 0x00. The calculation is built around that point.
First, a string is a contiguous sequence of byte addresses, so it can be read directly as a 32-bit value; call it
v.Then, if a byte is 0x00, subtracting 0x01 from that byte should cause a borrow, i.e.
(v - lomagic). Using& ~vcan tell whether a borrow happened.If the borrow goes past the most significant bit, it is 0xFF; then
& himagicis used to check further.If that's hard to follow, here's a concrete example
Suppose the 4 bytes of the string currently being checked are {0x11, 0x22, 0x33, 0x00}. Reading directly from the address gives v = 0x00332211.
Suppose the 4 bytes currently being checked are {0x11, 0x22, 0x33, 0x44}. Reading directly from the address gives v = 0x44332211.
Advantage
On some chips, checks like
if(v == 0x00)are very time-consuming. Using these simple bitwise calculations to get the value avoids this problem.