Mus
Mus

Reputation: 7540

Change Value of First Bit in Binary String - Java

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.

Upvotes: 1

Views: 814

Answers (1)

NPE
NPE

Reputation: 500713

You could use the following:

chromosome ^= 0x80;

The xor-assignment (^=) flips the chromosome bits that are set in the right-hand side expression, and 0x80 is 10000000 in binary.

More generally, to flip the k-th bit (with the least significant bit being bit 0):

chromosome ^= (1 << k);

Upvotes: 5

Related Questions