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)
The obvious portable, high efficiency method is:
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
testblockat runtime:By definition, static variables are automatically initialized to zero unless there is an initializer.