Bitwise Operators in C
Bitwise Operators in C
Bit-level operators make C useful for many low-level applications. Bitwise operations allow you to read and manipulate individual bits in variables of certain types.
The bitwise operators work only on int and char data types.
The following are the bitwise operators in C:
Operator | Description |
~ | Bitwise Complement |
<< | Bitwise Shift Left |
>> | Bitwise Shift Right |
& | Bitwise AND |
^ | Bitwise EX-OR |
| | Bitwise OR |
Bitwise operations helps to work on Boolean variable, which needs only one bit.Set membership can be represented with Boolean variables ( 1 means element in the set 0 means not in the set) and the Bitwise-AND can be used to implement set-intersection and Bitwise-OR to implement set union.
The bitwise AND(&) is true only if both bits are set. The bitwise OR(|) is false only when both the bits are false. The bitwise EX-OR operation returns 1 if the input bits are different.
The following chart defines these bitwise binary operations
Variable | Decimal Equivalent | B3 | B2 | B1 | B0 |
x | 12 | 1 | 1 | 0 | 0 |
y | 10 | 1 | 0 | 1 | 0 |
x&y | 8 | 1 | 0 | 0 | 0 |
x|y | 14 | 1 | 1 | 1 | 0 |
x^y | 6 | 0 | 1 | 1 | 0 |
Variable | Decimal Equivalent | B3 | B2 | B1 | B0 |
x | 12 | 1 | 1 | 0 | 0 |
~x | 3 | 0 | 0 | 1 | 1 |
Eg:
int x=5 // 0000 0000 0000 0101
y=x<<2; // x is shifted left two times and the result is stored in y.
so y become 20 //0000 0000 0001 0100
z=x>>2;// x is shifted right two times and the result is stored in z
so z become 1 // 0000 0000 0000 0001
void main()
{
int n;
printf("enter the number..\n");
scanf("%i",&n);
if(n & 0x00000001)
printf("odd\n");
else
printf("even\n");
}
2.Check whether the given number is a power of 2.
#include <stdio.h>
int main()
{
int n;
printf("Enter the number..\n");
scanf("%d",&n);
if(n & (n-1)==0)
printf("The number is Power of 2\n");
else
printf("The number is not power of 2\n");
return 0;
}
3.Exchanging the values of two variables with out using a temporary variable
#include <stdio.h>
int main()
{
int a,b;
printf("Enter the a and b..\n");
scanf("%d %d",&a,&b);
a=a^b;
b=b^a;
a=a^b;
printf("The swapped values of a and b\n",a,b);
return 0;
}
4.16 bit Binary equivalent of an integer number
#include <stdio.h>
void main()
{
unsigned short int n,i;
unsigned short int mask=0x8000;
int t;
printf("enter the number..\n");
scanf("%hu",&n);
for(i=0;i<16;i++)
{
t=n&mask;
putchar(t==0?'0':'1');
n=n<<1;
}
printf("\n");
}
void main()
{
unsigned short int n;
int count=0;
unsigned short int mask=0x8000;
printf("enter the number..\n");
scanf("%hu",&n);
while(mask!=0)
{
if(n & mask)
{printf("1");count++;}
else
printf("0");
mask=mask>>1;
}
printf("\nNumber of ones=%d\n",count);
void main()
{
int n,i,x,le=-1,so=9999;
printf("enter n..\n");
scanf("%i",&n);
printf("enter %d numbers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
if(x & 0x00000001)
{if(x<so) so=x;}
else
{if(x>le) le=x;}
}
printf("Largest even=%d smallest odd=%d\n",le,so);
}
Comments
Post a Comment