Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether all bytes in a memory block are zero

Tags:

c++

I have a block of memory with elements of fixed size, say 100 bytes, put into it one after another, all with the same fixed length, so memory looks like this

<element1(100 bytes)><element2(100 bytes)><element3(100 bytes)>... 

In some situations I need to determine whether all bytes of a certain element are set to the 0-byte because that has a special meaning (I didn't say it was a good idea, but that is the situation I am in).

The question is, how do I do that efficiently. Further: is there a simple function to do it. For setting bytes to zero I can used memset or bzero, but I don't know of any function for checking for zero.

At the moment I am using a loop for the check

char *elementStart = memoryBlock + elementNr*fixedElementSize; bool special = true; for ( size_t curByteNr=0; curByteNr<fixedElementSize; ++curByteNr ) {   special &= (*(elementStart+curByteNr)) == 0; } 

Of course, I could loop with a bigger offset and check several bytes at once with a mword or some other suited bigger type. And I guess that would be rather efficient, but I would like to know whether there is a function to take that burden from me.

Suggested functions:

  • !memcmp (compareBlock, myBlock, fixedElementSize)
like image 612
Ansgar Lampe Avatar asked Aug 04 '11 08:08

Ansgar Lampe


2 Answers

You could perhaps actually use memcmp without having to allocate a zero-valued array, like this:

static int memvcmp(void *memory, unsigned char val, unsigned int size) {     unsigned char *mm = (unsigned char*)memory;     return (*mm == val) && memcmp(mm, mm + 1, size - 1) == 0; } 

The standard for memcmp does not say anything about overlapping memory regions.

like image 184
mihaif Avatar answered Sep 19 '22 22:09

mihaif


The obvious portable, high efficiency method is:

char testblock [fixedElementSize]; memset (testblock, 0, sizeof testblock);  if (!memcmp (testblock, memoryBlock + elementNr*fixedElementSize, fixedElementSize)    // block is all zero else  // a byte is non-zero 

The library function memcmp() in most implementations will use the largest, most efficient unit size it can for the majority of comparisons.

For more efficiency, don't set testblock at runtime:

static const char testblock [100]; 

By definition, static variables are automatically initialized to zero unless there is an initializer.

like image 21
wallyk Avatar answered Sep 20 '22 22:09

wallyk