Search code examples
c++randombitmemsetpacking

How do I scramble the bits in a struct?


I have a pair of pack/unpack functions that operates on a structure of data.

In order to effectively unit test them,
I would like to put this structure into a random state, and then verify that the packing and unpacking returns the original structure. It might look something like this:

for (int i = 0; i < LOTS_OF_TESTS; ++i){
    Struct s;
    randomize_bits(s);
    CHECK ( s == UnPack(Pack(s)) );
}

Is there a function that takes a generic type, and randomizes all of the bits?

Conditions:
- There are no pointers in the structure
- There could be fundamental types
- There could be nested structs
- There could be arrays
- I'm not concerned about padding


I thought I might be able to use something with memset,
buy my attempt is giving me a runtime exception.

template<typename T>
void randomize_bits(T & t){
    for (size_t i = 0; i < sizeof(t); ++i){
        std::memset((&t)+i,random_uchar(),1);
    }
}

Solution

  • As suggested by Basile, this solves my problem, and iterates over the memory correctly.

    template<typename T>
    void randomize_bits(T & t){
        for (size_t i = 0; i < sizeof(t); ++i){
            reinterpret_cast<unsigned char*>(&t)[i] = random_uchar();
        }
    }