I have a program which works with genetic algorithms and generates an 8-bit binary string (chromosome consisting of eight genes).
I would like to know how I would go about changing / flipping the first gene/bit.
For example:
Original chromosome:
01010101
Changed chromosome:
11010101 //First bit has been changed
If the first bit has a value of 1, I would like to ‘flip’ it to make it a 0; and, obviously, if the first bit in the array/chromosome is a 0, I would like to ‘flip’ that to a 1.
Thank you.
You could use the following:
The xor-assignment (
^=) flips thechromosomebits that are set in the right-hand side expression, and0x80is10000000in binary.More generally, to flip the
k-th bit (with the least significant bit being bit 0):