A dirty re-write of the code in Why does this implementation of strlen() work?. Did some quick tests; no guarantees.
This should return the number of 0xFF
bytes; if it equals the number you started it with, you are in the safe. (Of course you could just let it return 0
or 1
as well.) Remove the printf
s when satisfied.
#define LONGPTR_MASK (sizeof(long) - 1)
int find_no_ff (const char *memory, size_t length)
{
const char *p;
const unsigned long *lp;
size_t remain = length, to_do;
printf ("non-aligned, start:\n");
/* Test the first few bytes until we have an aligned p */
for (p = memory; (uintptr_t)p & LONGPTR_MASK; p++)
{
printf ("testing %02X\n", *p & 0xff);
if (*p != '\xFF')
return (p - memory);
remain--;
}
printf ("passed.\n");
printf ("aligned:\n");
to_do = remain/sizeof(long);
remain -= (to_do*sizeof(long));
/* Scan the rest of the string using word sized operation */
for (lp = (const unsigned long *)p; to_do--; lp++)
{
printf ("testing %08lX\n", *lp);
if (*lp +1)
return p - memory;
}
printf ("passed.\n");
p = (const char *)lp;
printf ("non-aligned, end:\n");
/* Test the last bytes until we have an aligned p */
while (remain--)
{
printf ("testing %02X\n", *p & 0xff);
if (*p != '\xFF')
return (p - memory);
p++;
}
printf ("passed.\n");
return p - memory;
}
int main (void)
{
char data[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
printf ("input size: %ld\n", sizeof(data));
printf ("test result: %d\n", find_no_ff (data, sizeof(data)));
return 0;
}
memcmp
should allow for the best method as the compiler would be able to specialize for a known/constant size. – Africanist