Monday 13 July 2020

Bitwise Operator Complete solution

Bitwise operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits. Bit wise operators in C language are given below.

1. & (bitwise AND)
2. | (bitwise OR) 
3. ~ (bitwise NOT)
4. ^ (XOR)
5. << (left shift) 
6. >> (right shift).

Truth Table of bitwise operators

bitwise operator truth table

Example : 


#include<stdio.h>
/*============================
     Girfa Student Help
     Bitwise Operators
==============================*/
// C Program example of bitwise operators
#include <stdio.h>
void  main()
{
     // a = 5(00000101), b = 9(00001001)
     unsigned char a = 5, b = 9;

     // The result is 00000001
     printf("a = %d, b = %d\n", a, b);
     printf("a&b = %d\n", a & b);

     // The result is 00001101
     printf("a|b = %d\n", a | b);

     // The result is 00001100
     printf("a^b = %d\n", a ^ b);

     // The result is 11111010
     printf("~a = %d\n", a = ~a);

     // The result is 00010010
     printf("b<<1 = %d\n", b << 1);

     // The result is 00000100
     printf("b>>1 = %d\n", b >> 1);

}

Operator
Description
Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) = 12, i.e., 0000 1100
|
Binary OR Operator copies a bit if it exists in either operand.
(A | B) = 61, i.e., 0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) = 49, i.e., 0011 0001
~
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) = ~(60), i.e,. 1100 0011
<< 
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 = 240 i.e., 1111 0000
>> 
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 = 15 i.e., 0000 1111






No comments:

Post a Comment