Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. size_t strlen2(const char *str) {
  2.     const char *char_ptr;
  3.     const unsigned long int *longword_ptr;
  4.     unsigned long int longword, magic_bits, himagic, lomagic;
  5.  
  6.     for (char_ptr = str; ((unsigned long int) char_ptr & (sizeof(longword) - 1)) != 0; ++char_ptr)
  7.         if (*char_ptr == '\0')
  8.             return char_ptr - str;
  9.  
  10.     longword_ptr = (unsigned long int *) char_ptr;
  11.     magic_bits = 0x7efefeffL;
  12.     himagic = 0x80808080L;
  13.     lomagic = 0x01010101L;
  14.     if (sizeof(longword) > 4) {
  15.         magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL;
  16.         himagic = ((himagic << 16) << 16) | himagic;
  17.         lomagic = ((lomagic << 16) << 16) | lomagic;
  18.     }
  19.     if (sizeof(longword) > 8)
  20.         abort();
  21.  
  22.     while (1) {
  23.         longword = *longword_ptr++;
  24.         if (((longword - lomagic) & himagic) != 0) {
  25.             const char *cp = (const char *)(longword_ptr - 1);
  26.  
  27.             if (cp[0] == 0)
  28.                 return cp - str;
  29.             if (cp[1] == 0)
  30.                 return cp - str + 1;
  31.             if (cp[2] == 0)
  32.                 return cp - str + 2;
  33.             if (cp[3] == 0)
  34.                 return cp - str + 3;
  35.             if (sizeof (longword) > 4) {
  36.                 if (cp[4] == 0)
  37.                     return cp - str + 4;
  38.                 if (cp[5] == 0)
  39.                     return cp - str + 5;
  40.                 if (cp[6] == 0)
  41.                     return cp - str + 6;
  42.                 if (cp[7] == 0)
  43.                     return cp - str + 7;
  44.             }
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement