So I've been browsing though some of the older posts in the forums and I cam across
this from
Magmai Kai Holmlor:
int strlen(const char* cszStr)
{
DWORD* p = (DWORD*) cszStr;
DWORD k,kk;
while(DWORD(p)&3)
{
if(*(char*)(p)==0)
return (char*)(p)-cszStr;
p = (DWORD*) (((char*)(p)) + 1);
}
do
{
k = *p;
kk = k + 0x7efefeff;
k ^= -1;
k ^= kk;
p++;
} while(!(k&0x81010100));
k = *(--p);
if(!(k&0x000000ff))
return (char*)(p)-cszStr;
//if(!(k&0x0000ffff)) Thanks Kippesoep! [smile]
if(!(k&0x0000ff00))
return (char*)(p)-cszStr+1;
if(!(k&0x00ff0000))
return (char*)(p)-cszStr+2;
if(!(k&0xff000000))
return (char*)(p)-cszStr+3;
return (char*)(p)-cszStr;
}
Looked fairly interesting so I gave it a try. Worked good for the most part, except when the string sent in is one character, as seen in this demo program:
int main( int argc, char* argv[] )
{
char* str = "";
// Returns 0 (as expected)
printf("Length of %s: %i\n", str, __strlen__(str) );
// Returns 2 (not as expected)
str = "a";
printf("Length of %s: %i\n", str, __strlen__(str) );
// Returns 2 (as expected)
str = "ab";
printf("Length of %s: %i\n", str, __strlen__(str) );
// Returns 100 (as expected)
str = "1111111111__________1111111111__________1111111111__________1111111111__________1111111111__________";
printf("Length of %s: %i\n", str, __strlen__(str) );
// Returns 3 (as expected)
char temp[256] = { '1', '2', '3', '\0' };
printf("Length of %s: %i\n", temp, __strlen__(temp) );
}
So does anyone have any ideas to how it can work for a character of length 1? In particular, is this algorithm 'acceptable' to find the length of a string? This is just for knowledge and understanding, so please no "use strlen()" or "use std::string.size()" [wink]. Thanks!
[Edited by - Drew_Benton on April 26, 2005 2:34:33 AM]