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

后端 未结 10 702
渐次进展
渐次进展 2021-02-03 21:05

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

&l         


        
10条回答
  •  清酒与你
    2021-02-03 21:50

    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.

提交回复
热议问题