bit manipulation - C++ bitwise operations on structs and classes -


i'm developing generic genetic algorithm library, chromosome of each organism bit representation in memory. so, instance, if want mutate organism, flip bits of object randomly.

at first, tried using bitset class c++ standard library, but, when converting object t, option using to_ullong member function, problem representations number of bits larger size of unsigned long long.

then decided create generic library bitwise operations on object t, apply these operations directly onto objects themselves, instead of converting them first bitset.

so can see i'm trying achieve, here's function library:

template<typename t> void flip(t& x, size_t const i) {     x ^= 1 << i; } 

and it's used in ga library this:

template<typename t> void geneticalgorithm<t>::mutate(t& organism, double const rate) {     std::random_device rd;     std::mt19937 mt(rd());      std::uniform_real_distribution<double> dist(0, 1);      for(size_t = 0; < m_nbits; ++i)         if(dist(mt) <= rate)             bit::flip(organism, i); } 

it nice if worked, i'm getting error message vc++ 2015 rc compiler:

severity code description project file line error c2677 binary '^': no global operator found takes type 't' (or there no acceptable conversion) geneticalgorithm path\geneticalgorithm\geneticalgorithm\bitmanip.hpp 57

if correct error ^, more other operators.

i haven't used bitwise operators before in code, guess these operators not supposed used object? if so, how work around problem?

what want achieve can done (see peter schneider's comment):

template<typename t> void flip(t& x, size_t const i) {     unsigned char* data = reinterpret_cast<unsigned char*>(&x);     data[i/8] ^= (1 << (i%8)); } 

what reinterpreting data x array of bytes (unsigned char), determining byte should flipped (i/8), bit within byte (i%8).

note: in addition, may safe add @ beginning of function:

assert(i < sizeof(t)*8) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -