如何更新二进制数的一位作为切换? [英] How to update a single bit of a binary number as toggle?

查看:121
本文介绍了如何更新二进制数的一位作为切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这张桌子:

// numbers
+---------+------------+
|    id   |    numb    |
+---------+------------+
| int(11) |   bit(10)  |
+---------+------------+
| 1       | 1001100111 |
| 2       | 0111000101 |
| 3       | 0001101010 |
| 4       | 1111111011 |
+---------+------------+

我正在尝试更改(切换)第七位数字(从右到左)的值.因此,请专注于该数字:

I'm trying to change (toggle) the value of seventh digit (right to left). So focus on this digit:

// for example
1001100111
  ^ seventh digit (rtl)

这是预期的结果:

// new_numbers
+---------+------------+
|    id   |    numb    |
+---------+------------+
| int(11) |   bit(10)  |
+---------+------------+
| 1       | 1011100111 |
| 2       | 0101000101 |
| 3       | 0011101010 |
| 4       | 1101111011 |
+---------+------------+


我可以像这样更新第七位


I can update seventh digit like

// set it to zero
UPDATE numbers SET numb = numb & b'1110111111';

但是实际上我需要切换它.

But actually I need to toggle it.

  • 如果它是0,则将其设置为1
  • 如果它是1,则将其设置为0
  • if it is 0 then set it 1
  • if it is 1 then set it 0

我该怎么做?

推荐答案

通过XOR ^操作,使用您要切换的位置具有1的蒙版,对Xc ^操作进行翻转.

Flipping a bit is done by XOR ^ operation with a mask that has 1s in positions that you would like to toggle.

之所以起作用,是因为XOR的真值表如下所示:

This works because the truth table of XOR looks like this:

  A: 0 0 1 1
  B: 0 1 0 1
A^B: 0 1 1 0

请注意B1的列:当A中的对应位为零时,结果为1,反之亦然.

Note the columns where B is 1: when the corresponding bit in A is zero, the result is one, and vice versa.

切换第七位是这样的:

UPDATE numbers SET numb = numb ^ b'0001000000';

这篇关于如何更新二进制数的一位作为切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆