# 什么是位运算？

In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, simple action directly supported by the processor, and is used to manipulate values for comparisons and calculations. On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition. While modern processors usually perform addition and multiplication just as fast as bitwise operations due to their longer instruction pipelines and other architectural design choices, bitwise operations do commonly use less power because of the reduced use of resources.

# 位运算的逻辑运算符

1. & 与运算

1. | 或运算

x || y , x | y 不同的是，如果 x 为 true，则不计算 y（因为不论 y 为何值，“或”操作的结果都为 true）。这被称作为“短路”计算。

1. ^ 位异或

1. ~ 位非

# 应用实例

1 转换为二进制为 0001 2 转换为二进制为 0010 4 转换为二进制为 0100

6 & 1，即0110&0001=0000=0，表示不包含主管a的报价。

6 & 2，即0110&0010=0010>0，表示包含主管b的报价。

``````CREATE TABLE price
(
id INT PRIMARY KEY,
ap INT DEFAULT NULL,
bp INT DEFAULT NULL,
cp INT DEFAULT NULL,
p INT DEFAULT NULL
);

INSERT INTO price VALUES
(1,NULL,100,93,6),
(2,188,170,203,7),
(3,NULL,14,NULL,2);

INSERT INTO price VALUES
(4,NULL,NULL,NULL,NULL),
(5,44,55,66,7),
(6,NULL,NULL,430,4);

SELECT
id '产品编号',
CASE WHEN p&ap>0 THEN ap
WHEN p&bp>0 THEN bp
WHEN p&cp>0 THEN cp
ELSE '该产品无有效报价'
END '有效报价',
CASE WHEN p&ap>0 THEN 'ap'
WHEN p&bp>0 THEN 'bp'
WHEN p&cp>0 THEN 'cp'
ELSE '无'
END '报价主管'
FROM price;

—— 福利·贝热尔的吧台 马奈（晚年代表作）