I'm making a strchr implementation and trying to optimize my code to use the 64bit properties of my machine. So, I' converting my strings to long integers, thus comparing 8 chars at a time.
Currently, I have :
int has_char(unsigned long word, unsigned long c)
{
if((word & 0xFF00000000000000) == (c << 56) ) return (1);
if((word & 0x00FF000000000000) == (c << 48)) return (1);
if((word & 0x0000FF0000000000) == (c << 40)) return (1);
if((word & 0x000000FF00000000) == (c << 32)) return (1);
if((word & 0x00000000FF000000) == (c << 24)) return (1);
if((word & 0x0000000000FF0000) == (c << 16)) return (1);
if((word & 0x000000000000FF00) == (c << 8)) return (1);
if((word & 0x00000000000000FF) == c) return (1);
return (0); /* Not found, returning 0 */
}
char strchr(const char *s, int c)
{
const char *curr;
const long *str;
unsigned long wd;
str = (long *)s;
while (1) {
wd = *str;
if (has_char(wd, (unsigned long)c)) {
curr = (char *)str;
while (*curr) {
if (*curr == (char)c)
return ((char *)curr);
curr++;
}
}
if ((wd - 0x0101010101010101)
& ~wd & 0x8080808080808080) /* End of string and character not found, exit */
return (NULL);
str++;
}
}
It works well but my has_char is very inefficient, it tests 8 times for the character value. Is there a way to make a unique test (a mask ?) that will return 1 if the character is present in the word and 0 if it is not present ?
Thanks for your help !
Very well, here is the precise code as requested:
Beware: Written off the top of my head.