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

后端 未结 10 707
渐次进展
渐次进展 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:47

    Well if you just want to decide whether a single element is all 0s you can create a 100byte element with all 1s. Now when you want to check whether an element is all 0s just binary AND (&) the content of the element and the element you created(all 1s). now if the result of binary AND is zero the element you checked had all 0s otherwise it was not all 0s

    the creation of a 100 byte element with all 1s seems costly but if you have a large number of elements to check then its actually better

    you can create the 100 byte element with all 1s as void *elem; elem=malloc(100); now set all bits to 1(use ~(elem&0))

提交回复
热议问题