Bitwise Operators

 

Bitwise Logical Operators

Bitwise logical operators are used to perfor bit setting, clearing, inversion, and complement operations on integral variables or hardware registers.

 

Masking examples (variables are assumed to be char in these examples):

result = inputch & 0x80;   //clear all but the msb

newval = ctrlch & ~0x80;  //clear msb (note that the one’s complement of 0x80 is 0x7f)

mask = keychar | 0x80;     //set msb

newch = oldch ^ 1;          // invert lsb

 

if (field & bitmask)

          //  at least one of the bits is set

 

 

 

Bitwise Shift Operators(for use with integral arguments only):

 

Shifting is Multiplying and Dividing – Say what?

A binary left shift is the same as doubling the value or multiplying by 2.

A binary right shift is the same as halving the value or dividing by 2.

Left shifts introduce zeros from the right. Right shifts introduce bits that match the current msb. Thusly, the sign of the original value is preserved, if that is important.

 

newfld = oldfld << 3;        //shift 3 bits left (multiplys by 8)

mydaya = yourdata >> 2:   // shift 2 bits right (divides by 4)

 

 

The std::hex Manipulator is used in this section of the text and will be covered later in this lesson.