开发者

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 开发者_Python百科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:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜