3.3 Logical Operations on Binary Numbers and Bit Strings


3.3 Logical Operations on Binary Numbers and Bit Strings

The logical functions work on single-bit operands. Because most programming languages manipulate groups of 8, 16, or 32 bits, we need to extend the definition of these logical operations beyond single-bit operands. We can easily extend logical functions to operate on a bit-by-bit (or bitwise ) basis. Given two values, a bitwise logical function operates on bit zero of both operands producing bit zero of the result; it operates on bit one of both operands producing bit one of the result, and so on. For example, if you want to compute the bitwise logical AND of two 8-bit numbers, you would logically AND each pair of bits in the two numbers:

 %1011_0101  %1110_1110  ---------- %1010_0100 

This bit-by-bit execution also applies to the other logical operations, as well. The ability to force bits to zero or one using the logical AND and OR operations, and the ability to invert bits using the logical XOR operation, is very important when working with strings of bits (such as binary numbers). These operations let you selectively manipulate certain bits within a value while leaving other bits unaffected. For example, if you have an 8-bit binary value X and you want to guarantee that bits four through seven contain zeros, you could logically AND the value X with the binary value %0000_1111. This bitwise logical AND operation would force the HO four bits of X to zero and leave the LO four bits of X unchanged. Likewise, you could force the LO bit of X to one and invert bit number two of X by logically ORing X with %0000_0001 and then logically exclusive ORing (XORing) X with %0000_0100. Using the logical AND, OR, and XOR operations to manipulate bit strings in this fashion is known as masking bit strings. We use the term masking because we can use certain values (one for AND, zero for OR and XOR) to 'mask out' or 'mask in' certain bits in an operand while forcing other bits to zero, one, or their inverse.

Several languages provide operators that let you compute the bitwise AND, OR, XOR, and NOT of their operands. The C/C++/Java language family uses the ampersand ( & ) operator for bitwise AND, the pipe () operat or for bitwise OR, the caret (^) operator for bitwise XOR, and the tilde (~) operator for bitwise NOT. The Visual Basic and Delphi/Kylix languages let you use the and, or, xor , and not operators with integer operands. From 80x86 assembly language, you can use the AND, OR, NOT, and XOR instructions to do these bitwise operations.

 // Here's a C/C++ example:      i = j & k;    // Bitwise AND      i = j  k;    // Bitwise OR      i = j ^ k;    // Bitwise XOR      i = ~j;       // Bitwise NOT 



Write Great Code. Understanding the Machine, Vol. 1
The Art of Assembly Language
ISBN: 1593270038
EAN: 2147483647
Year: 2003
Pages: 144
Authors: Randall Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net