strlen实现

size_t my_strlen(const char* str)
{
    const char* ptr = str;
    for (; ((int)ptr & 0x03) != 0; ++ptr)
    {
        if (*ptr == '')
            return ptr - str;
    }

    unsigned int* ptr_d = (unsigned int*)ptr;
    unsigned int magic = 0x7efefeff;
    //01111110    11111110    11111110     11111111 

    while (true)
    {
        unsigned int bits32 = *ptr_d++;
        if ((((bits32 + magic) ^ (bits32 ^ -1)) & ~magic) != 0) // bits32 ^ -1 等价于 ~bits32
        {
            ptr = (const char*)(ptr_d - 1);
            if (ptr[0] == 0)
                return ptr - str;
            if (ptr[1] == 0)
                return ptr - str + 1;
            if (ptr[2] == 0)
                return ptr - str + 2;
            if (ptr[3] == 0)
                return ptr - str + 3;
        }
    }
}
原文地址:https://www.cnblogs.com/yifi/p/6696291.html