strlen实现

size_t my_strlen(const char* str)
{
    const char* ptr = str;
    for (; ((int)ptr & 0x03) != 0; ++ptr)
    {
        if (*ptr == '\0')
            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;
        }
    }
}

 

posted on 2017-04-11 21:05  yifi  阅读(227)  评论(1编辑  收藏  举报

导航