There are 6 bit operations: 7 P "@ 3 D5 Q ']

&And operation 5 J5 W: I! o% L/ ]

|Or operation

^Exclusive or operation! {\$ V2 U b; h. Y- ?8 p" e

~Non operation (complement)

Shift right operation

< < left shift operation

• r, S ! T) 1 Y/ ^2 P

And operation (&) (P "G & E5 ~ / J # U * s' l

Binocular operation. When both bits are set (equal to 1), the result is equal to 1, and the other results are equal to 0* W+ U/ q9 W: h; |: v1 ]9 V

1 & 1 == 1

1 & 0 == 0

0 & 1 == 0

0 & 0 == 0 + ~! | {1 u* x( n/ N/ O

8 e% n& Q0 }; ?! t" g f i8 C

One use of the and operation is to check whether the specified bit is set (equal to 1). For example, there is an identification bit in a byte. To check whether the fourth bit is set, the code is as follows: 4 Z - J ^ 8 y '@ (F: G

BYTE b = 50; , v# z. m8 l# }4 s6 l3 e# S

if ( b & 0x10 ) " x; n, c4 Z. u: J- }

cout << "Bit four is set" << endl;

else

cout << "Bit four is clear" << endl;

The above codes can be expressed as:

• R; D2 m ~5 m q! M

00110010 - b

& 00010000 - & 0x10 9 ^" p0 k7 N& t* [

---------------------------- 9 k5 K\$ k\$ m" s, K9 k

00010000 - result , ^+ D* p7 v/ f2 q3 h+ l

( n# ]+ t1 a! x0 Q5 j) g

It can be seen that the fourth bit is set.

Or operation (|)

Binocular operation. As long as there is one position bit between the two bits, the result is equal to 1. When both bits are 0, the result is 0.

1 | 1 == 1 4 u9 }1 j# P( r

1 | 0 == 1 9 J4 g. H3 X8 r\$ z" h, B5 K

0 | 1 == 1 2 A/ K+ R9 B0 W0 D* o& g

0 | 0 == 0 ( # j# L* V6 R8 M7 A+ C

8 l6 q; g7 T5 u7 {+ P, @9 a+ N

The and operation can also be used to check the setting. For example, to check whether the 3rd bit of a value is set: * e & U6 m! j; r; l2 Y+ }

BYTE b = 50;

BYTE c = b | 0x04; . }. y) i\$ A9 Z' M

cout << "c = " << c << endl; & }% a7 `4 p\$ j& F7 g# ~

It can be expressed as + I. X - a a! i: u1 `7 m3 {

; B } V4 f5 i6 x\$ s

00110010 - b ) \6 p0 P\$ W5 S( r+ k! Z! h

| 00000100 - | 0x04

---------- ! {0 J3 g) {& R y

00110110 - result

Exclusive or (^) \$[3 P / D (F, u # C6 J8 f

Binocular operation. When the two bits are not equal, the result is 1; otherwise, it is 0.

1 ^ 1 == 0 \$ y5 s( i; d" B

1 ^ 0 == 1 o' J( Z( `, ~9 X' F

0 ^ 1 == 1

0 ^ 0 == 0 - N' a( |; N2 z |9 m2 T

; e9 T5 k\$ e6 {. N- u\$ r

The exclusive or operation can be used for bit value inversion. For example, flip the values of the 3rd and 4th bits:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.