简体   繁体   中英

How do bit manipulators work in mySQL (with this example)

This is an example for bit manipulation. I do not understand how (id+1)^1-1 gives the shown output values. Please help.

Bit manipulation expression (id+1)^1-1 can calculate the new id after switch.

SELECT id, (id+1)^1-1, student FROM seat;


| id | (id+1)^1-1 | student |

|----|------------|---------|

| 1  | 2          | Abbot   |

| 2  | 1          | Doris   |

| 3  | 4          | Emerson |

| 4  | 3          | Green   |

| 5  | 6          | Jeames  |

^ is the bitwise XOR-operator. Bitwise x XOR 1 switches the last bit of x ( 1 xor 1 = 0 , 0 xor 1 = 1 ), so it exchanges 0 and 1, 2 and 3 and so on.

So now you have a way to switch seats 0 and 1, 2 and 3, or, for this matter, seats 2 and 3, 3 and 4.

To use this to exchange 1 with 2, 3 and 4, you can first map 1, 2, 3, 4 to 2, 3, 4, 5 , apply the XOR , then map the result back to 1, 2, 3, 4 .

The function that maps 1, 2, 3, 4 to 2, 3, 4, 5 is f(x) = x+1 . The reverse is g(x) = x-1 .

So what you get is: h(x) = g( xor1( f(x) ) ) . This is exactly your formula: apply ^1 to id+1 , (id+1)^1 , then undo the subsitution by applying x-1 to this result, and you get ((id+1)^1)-1 .

Another substitution would have been to map 1, 2, 3, 4 to 0, 1, 2, 3 (with f(x) = x-1 and g(x) = x+1 ), giving you the final formula ((id-1)^1)+1 .

Let me present you how it is done:

first, ^ is XOR operation, so:

0^0 = 0
1^0 = 1
0^1 = 1
1^1 = 0

Note that 1 = 001 in binary form (I presented only relevant 3 bits to below explanation), so for example 2^1 = 010^001 :

    010
XOR 001
-------
    011 = 3

id |  binary id | id + 1 | binary id + 1 | binary (id + 1) ^ 1 | decimal (id + 1) ^ 1 | (id + 1) ^ 1 - 1
1  |  001       | 2      | 010           | 011                 | 3                    | 2
2  |  010       | 3      | 011           | 010                 | 2                    | 1
3  |  011       | 4      | 100           | 101                 | 5                    | 4
4  |  100       | 5      | 101           | 100                 | 4                    | 3
5  |  101       | 6      | 110           | 111                 | 7                    | 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM