DEV Community

Cover image for MANIPULATING BITS
Sachin aralapura
Sachin aralapura

Posted on

MANIPULATING BITS

BITWISE OPERATORS

In cases where conservative use of memory is imperative, data often need to be bit coded,
a technique to represent information as individual bits. Some examples of bit coded data
can be found in file access rights or the status-word of a stream.

To access bit coded data, you need to be able to read or modify individual bits. C++
has six bitwise operators to perform these tasks:

Logical bitwise operators

& - AND

^ - exclusive OR

| - inclusive OR

~ - NOT
Enter fullscreen mode Exit fullscreen mode

Bitwise shift operators

<< - Left shift

\>> - right shift
Enter fullscreen mode Exit fullscreen mode

operands for bitwise opertor must be integer
, if bit value is 1 , it will be interpreted as true , else false

The result type of a bitwise operation will be the integral type defined by the operand type.

Arithmetic Type Conversions

If the operands of bitwise operator are different , then the operands are converted .

Example : If one operand is Int and other is long , then the long is converted to Int .

The difference between & or | and logical && and || operator is later doesn't effect the individual bits but interprets the whole value of their operands as boolean returning a boolean value.

The expression 1 && 2 returns the value true, whereas 1 & 2 has the value 0.
Enter fullscreen mode Exit fullscreen mode

BITWISE SHIFT OPERATORS

The shift operators << and >> shift the bit pattern of their left operand a certain number of bit positions. The number of positions is defined by the right operand.

In the case of a left shift, 0 bits are padded. The bits dropped on the left are lost.

In the case of a right shift, 0 bits are padded from the left

example

short x = 0x08;     // 0000 1000
x =  x << 1;        // after shifting 0001 0000
cout << hex << x << endl;   // output  80
Enter fullscreen mode Exit fullscreen mode

Applications

Shift operators allow you to perform efficient multiplication and division with 2^n
Shifting a number n places left (or right) is equivalent to a multiplication (or division) by 2^n.

BIT MASKS

#define MASK 0x20
char c = 'A';
c = c | MASK;
Enter fullscreen mode Exit fullscreen mode

Deleting Bits

The bitwise AND operator is normally used to delete specific bits. A so-called mask is used to determine which bits to delete.

Setting and Inverting Bits

You can use the bitwise OR operator | to set specific bits. The example above shows how to change the case of a letter. In ASCII code, the only difference between a lowercase and an uppercase letter is the fifth bit.

Bitwise Operators in Compound Assignments

The binary bitwise operators &, |, ^, <<, and >> can be used in compound assignments.

Examples: x >>= 1;
          x ^= 1;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)