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

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

    The following will iterate through the memory of a structure. Only disadvantage is that it does a bytewise check.

    #include 
    
    struct Data { int i; bool b; };
    
    template
    bool IsAllZero(T const& data)
    {
        auto pStart = reinterpret_cast(&data);
        for (auto pData = pStart; pData < pStart+sizeof(T); ++pData)
        {
            if (*pData)
                return false;
        }
    
        return true;
    }
    
    int main()
    {
        Data data1;// = {0}; // will most probably have some content
        Data data2 = {0}; // all zeroes
    
        std::cout << "data1: " << IsAllZero(data1) << "\ndata2: " << IsEmptyStruct(data2);
    
        return 0;
    };
    

提交回复
热议问题