When you program in a COBOL environment, you deal with data that is composed of characters, fields, records, or files. However, there are occasions when you must deal with individual data bits. For example, bit manipulation is an important feature in applications that deal with:
There is a set of library routines for bit manipulation. These routines are:
These logical operations give the results shown in the following truth table.
For example, when the CBL_EQ routine compares bits A and B, the resulting bit is set to 1 if both A and B are 0 or if both A and B are 1. Otherwise the resulting bit is set to 0.
You can also define data items as boolean using picture character 1, and use the boolean operators B-AND, B-OR, B-XOR, and B-NOT to perform "and", "or", "exclusive or", and "negate" operations. These operators are used in boolean expressions; for example:
01 My-flag PIC 1111 USAGE BIT VALUE B"0000". 01 My-flag-2 PIC 1111 USAGE BIT. ... MOVE B"0011" to My-flag-2 *> Initialize My-flag-2 ... COMPUTE My-flag = B-NOT My-flag-2 *> set the bits in My-flag to the *> reverse of My-flag-2, 1100. ... COMPUTE My-flag = My-flag B-AND B"0000" *> turn off all the bits in My-flag. ... COMPUTE My-flag-2 = My-flag-2 B-OR B"1000" *> set bit 1 ON in My-flag-2, keeping *> other bits unchanged.
Boolean items can be tested in two ways:
01 Single-bit-item pic 1 usage bit. 01 Multiple-bit-item pic 1(7) usage bit. ... IF Single-bit-item THEN CALL a-program *> calls if Single-bit-item is true (1)
IF My-flag-2 EQUAL B"1000" THEN CALL a-program
Boolean items can be converted to integer with the INTEGER-OF-BOOLEAN intrinsic function, and integer items can be converted to boolean with the BOOLEAN-OF-INTEGER intrinsic function. For example:
01 bit-item PIC 1(6) usage BIT. 01 integer-item PIC 9(5) VALUE 544. *> 1000100000 in binary 01 integer-item-2 PIC 9(3). ... MOVE FUNCTION BOOLEAN-OF-INTEGER ( integer-item , 6) TO bit-item. *> the function returns the low order 6 bits of the binary representation of the *> integer value, and MOVE stores it in bit-item, padding on the right with 0’s ... COMPUTE integer-item-2 = FUNCTION INTEGER-OF-BOOLEAN (bit-item). *> the function returns the numeric value of the leading 6 bits (100000 in binary), 32, and *> COMPUTE puts 032 in integer-item-2