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

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

    I can't believe no one posted this yet... a solution that actually looks like C++ and isn't UB for breaking aliasing rules:

    #include  // std::all_of
    #include    // std::size_t
    
    // You might only need this
    bool
    memory_is_all_zeroes(unsigned char const* const begin,
                         std::size_t          const bytes)
    {
        return std::all_of( begin, begin + bytes,
                            [](unsigned char const byte) { return byte == 0; } );
    }
    
    // but here's this as a bonus
    template
    bool
    array_is_all_zeroes( T_Element const (& array)[T_count] )
    {
        auto const begin = reinterpret_cast(array);
        auto const bytes = T_count * sizeof(T_Element);
    
        return memory_is_all_zeroes(begin, bytes);
    }
    
    int
    main()
    {
        int const blah[1000]{0};
    
        return !array_is_all_zeroes(blah);
    }
    

    This might not satisfy some people's assumptions about efficiency (which are just that, assumptions, until profiled), but I think being valid and idiomatic code are much in its favour.

提交回复
热议问题