How to effectively compare a memory block with one byte?

I am trying to check if a structure has returned like everything 0xFFfor the size of the structure.

memcmpIt seems an obvious starting point, BUT I have to allocate a second block of memory, fill it 0xFF. It just seems like a waste.

Is there a standard function for this? Or do I just need to punt and iterate through a for loop?

+4
source share
6 answers

The most obvious solution here is to simply iterate over the size of the structure and compare it by byte.

The block allocation approach 0xFFthat follows memcmpshould achieve the same, but with a higher complexity of space.

+3

.

, memcmp ( ).

( ). ( ). , , ( ).

openmp ( , GCC). . http://openmp.org/

(, , - GPGPU โ†” ), , , OpenCL ( , GPGPU). ( -, - , GPGPU)

( , ), , , .

+3

memcchr - memchr, strcspn strspn.

: google memcchr , FreeBSD, 1 .

, , , FreeBSD.

+3

memchr(), , , - mem. afaik, , . . , 32/64 , .

- -: memcmp , for. -, , ( , , , ). , . for .

+2

, , :

  • 1- 1 0xFF
  • 1-
  • 3-4 1-2
  • 5-8 1-4

. - , , 0xFF. -, , .

1 , - O (log n) ( , ).

edit: escrafford, "" "" , . , , , ( ).

+2

strlen() ?. ; .

0xFF ; , , . (, 0 1.) printf, .

#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;
}
0

All Articles