更改二进制字符串中第一位的值 - Java

发布于 2024-12-08 19:32:58 字数 375 浏览 5 评论 0原文

我有一个程序,它与遗传算法一起工作并生成 8 位二进制字符串(由八个基因组成的染色体)。

我想知道如何改变/翻转第一个基因/位。

例如:

Original chromosome:
01010101

Changed chromosome:
11010101 //First bit has been changed

如果第一位的值为 1,我想将其“翻转”以使其变为 0;而且,显然,如果数组/染色体中的第一位是 0,我想将其“翻转”为 1

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你而言 2024-12-15 19:32:58

您可以使用以下内容:

chromosome ^= 0x80;

异或赋值 (^=) 翻转右侧表达式中设置的 染色体 位,以及 0x80 code> 的二进制形式为 10000000

更一般地说,翻转第 k 位(最低有效位为 0 位):

chromosome ^= (1 << k);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文