Wednesday, August 26, 2020

9.1.6 Bitwise Operators

  • Bitwise operators are used to perform bit level operations on given variables. 
  • The decimal values of the variables are converted to bits. 
  • After this the operations are performed on those bits. 
  • Below is the bitwise operators used in the C language.

Operators

 

Description

& (Bitwise AND)

This operator performs the AND operation with bits of the same

position of both the variables.

| (Bitwise OR)

This operator performs the OR operation with bits of the same

position of both the variables.

~ (Bit wise NOT)

These operators are used with just one operand.

The variable with which the variable is used is returned to the value of all the bits of that variable.

As if 0 is 1 then it becomes 1 and then 1 becomes

zero.

^ (XOR)

This is a special type of OR operator.

This operator returns 1 when the opposite is bits and returns 0 to the same bit.

<< (Left Shift)

This operator left side of the variable's bits in the left side of the variable in the variable of shift in the left side as shift.

>> (Right Shift)

The operator left side variables of the variables shift in the right side of the variable in the right.


EXAMPLE :-

// Bitwise operators in C.
#include <stdio.h>
int main()
{
    unsigned char x = 4, y = 15;

    printf("x = %d, y = %d\n", x, y);
    printf("x&y = %d\n", x & y);

    printf("x|y = %d\n", x | y);

    printf("x^y = %d\n", x ^ y);

    printf("~x = %d\n", x = ~x);

    printf("y<<1 = %d\n", y << 1);

    printf("y>>1 = %d\n", y >> 1);

    return 0;
}


OUTPUT


x = 4, y = 15 x&y = 4 x|y = 15 x^y = 11 ~x = 251 y<<1 = 30 y>>1 = 7


  • As you know, work with bitwise operators bits. 
  • Let's say you have created 2 variables a and b in the program. 
  • In these two variables, you have stored 3 and 5 values respectively. 
  • To work on their bits, first you can convert them into binary.
                      
                        3 = 00000011
                        5 = 00000101

  • They have been converted into binary only with the purpose of explaining to you. You do not need to insert binary values into the program. 
  • Store computer information only in binary form. 
  • All the operations defined above will be performed on these bits only.

No comments:

Post a Comment

Please do not any spam link in Comment Box