GAT - Bitwise Operator - Updated
GAT - Bitwise Operator - Updated
output:
10 & 6 =2
Bitwise OR
(I)
#include<stdio.h> If the corresponding bit
void main() positions in both the
{ operands are 0 , then OR
int a,b,c; operation results in 0,
a=10 otherwise OR operation
;
results in 1.
b=6;
c=a | 0 | 0 =0
b; 0 |1 =1
printf 1 |0 =1
(“%d
| %d= 1 |1 =1
%d\
n”, a,
b, c);
}
Bitwise XOR(^)
If the corresponding bit #include<stdio.h>
positions in both the void main()
operands are different , then {
ex-OR operation results in int a,b,c;
1, otherwise ex-OR a=10;
operation results in 0.
b=6;
The symbol used is called c=a^b
caret (^). ;
printf(
“%d ^
0^0=0
%d=
0 ^1 = 1 %d\n”,
1 ^0 = 1 a, b,
c);
1^1=0
}
output:
Bitwise complement (~)
#include<stdio.h>
The operator that is used
to change every bit from void main()
0 to 1 and 1 to 0 in the {
specified operand is unsigned char a,b;
called one‟s a=10;
complement operator.
b=~a;
The one‟s complement
operator is denoted by
the symbol “tilde”(~). printf(“~%d = %d\n”, a, b);
128 64 32 16 8 4 2 1
}
0 0 0 0 1 0 1 0
output:
1 1 1 1 0 1 0 1
~10=245
Bitwise Shift-Right Operator
The bitwise shift right (»—precedence 11 ) is a binary
operator that requires two integral operands (character or
integer).
The first operand is the value to he shifted.
The second operand specifies the number of hits to be
shifted.
Shifting binary numbers is just like shifting decimal
numbers.
When bits are shifted right, the hits at the rightmost end are
deleted.
Bitwise Shift-Left Operator
The bitwise shift right <<—precedence 11 ) is a binary operator that requires
two integral operands (character or integer).
The first operand is the value to be shifted.
The second operand specifies the number of hits to be shifted.
Multiplying by 2
Program showing bitwise left shift operation
#include<stdio.h>
Eg: b=5<<1;
void main()
The data 5 is shifted towards
left by 1 position as shown {
below and the result is stored int a,b;
in the variable b. a=5;
b=a<<1;
printf(“%d<<1
= %d\n”, a, b);
128 64 32 16 8 4 2 1 }
0 0 0 0 0 1 0 1
0 0 0 0 0 1 0 1 output:
5<<1=10
Program showing bitwise Right shift operation
#include<stdio.h>
Eg: b=10>>1; void main()
The data 10 is shifted {
towards right by1 position
as shown below and the int a,b;
result is stored in the a=10;
variable b. b=a>>1;
printf(“%d>>1=%d\n”, a, b);
}
128 64 32 16 8 4 2 1 0
output: 10>>1=5
0 0 0 0 1 0 1 0
0 0 0 0 1 0 1 0
Right shift (>>)
Example:
1. b=10>>1
Before :00001010
after:00000101
b=5
2. b=10>>3
00001010 00000001
b=1
Write output?
#include<stdio.h>
void main( )
{
int
a=7,b=3,x,y,z;
x=a & b; // bitwise AND
y= a | b; // bitwise OR
z= a ^ // bitwise XOR
b;
printf(“value of x=%d \n”,x);
printf(“value of y=%d \n”, y);
printf(“value of z=%d \n”, z);
printf(“value of ~a=%d \n”, ~a);
Output:
printf(“a left shift by 2 bits=%d\
n”, a<<2); value of x=3
printf(“ b right shift by 1 bits= value of y=7
%d\n”, b>>1); value of z=4
} value of ~a=-8
a left shift by 2 bits=28
b right shift by 1 bits=1
Rotation
Rotation requires that bits can be taken off the other end of a
value and moved to the other end.
When we rotate bits left, we shift them off the left end of the
value and insert them on right.
When we rotate right , we shift off the right end and insert them
on the left.
Appendix G(G.1-G.3)
Pre-processor Commands
G.1 File Inclusion
The preprocessor command is #include, and it has two different
formats.
The first format is used to direct the preprocessor to include header
files from the system library.
#include <filename.h>
The second format makes the preprocessor look for the header files
in the user-defined directory.
#include "filepath.h“
G.2 Macro Definition
The second preprocessor task is expanding macro
definition.
A macro definition command associates a name with a
sequence of tokens.
The name is called the macro name and the tokens are
referred to as the macro body
A macro definition has the following form:
#define name body
The body is the text that is used to specify how the name is
replaced in the program before it is translated
Two important issues in macros
1. Macros must be coded on a single line.
If the macro is too long to fit on a line, we must use a
continuation token.
The continuation token is a backslash ( \) followed
immediately by a newline.
If any whitespace is present between the backslash and the
newline, then the backslash is not a continuation token, and the
code will most likely generate an error.
#define PREND \
printf ("Normal end of program PA5-01./n");
2. We need to be careful in coding the macro body.
Whenever a macro call (name of the macro in the program)
is encountered, the preprocessor replaces the call with the
macro body.
If the body is not created carefully, it may create an error or
undesired result.
#define ANS = 0
// creates a compile error when it is used as shown below:
num = ANS;
//After preprocessing, the result would be
num ==0; //which is not what we wanted.
Coding Defined Constants
The simplest application of a macro is to define a constant.
#define SIZE 9
The name is SIZE and the body is 9. Whenever in the program
SIZE is encountered, it is replaced with 9.
The body of the macro definition can be any constant value including integer, real,
character, or string. However, character constants must be enclosed in single quotes and
string constants in double quotes
Macros That Simulate Functions
The preprocessor’s macro facility is very powerful.
It can even be used to simulate functions.
In this section we discuss using macros in place of functions, first for
functions with no parameters and then for functions with parameters.
1. Macros to Simulate Functions without Parameters
When we simulate a function with a macro, the macro definition replaces the
function definition.
The macro name serves as the header and the macro body serves as the
function body.
The name of the macro is used in the program to replace the function call.
2. Macros to Simulate Functions with Parameters
Done in 2 steps:
1. The body of the macro replaces the macro call with the same actual
parameters used in the macro definition.
2. The actual parameters are replaced with formal parameters.
Advantage of macros:
One of the advantages of using macros instead of function is type
independence.
We can define a PRODUCT macro that multiplies any two pairs of data type.
We need to give two warnings:
To include parameters in the macro, the opening parenthesis must be placed
immediately at the end of the macro name; that is, there can be no whitespace
between the macro name and the opening parenthesis of the parameter list. If
there is a space, then the opening parenthesis is considered part of the token
body and the macro is assumed to be simple.
It is a strong recommendation that the formal parameters, in the body of macro
be placed inside parentheses. The reason is that macro uses text replacement. It
replaces the actual parameters with formal parameters.
p=x*y
p = a + 1 * b + 2 ; y; // We need (a +1) * (b+2)
The solution would be to include the formal parameters inside parentheses.
In other words, make the parentheses part of body code.
#define PRODUCT(x, y) (x) * (y)
P=(x)*(y);
p = ( a + 1) * ( b + 2 ) ;
EXAMPLES:
Macros can replace many simple functions.
# define ROTATE_LEFT ( x , n ) \
( ( ( x ) « ( n ) ) | ( ( x ) » ( 32 - x ) ) )
We often need to use a power of 2 in a program. To
calculate 2x we can easily use the shift operator in a macro
as shown below:
#define POWER2 ( x ) 1 « ( x )
EXAMPLE 2.
Multi-Way Commands
Conditional commands can also be multi-way; selecting
one of the choices among several.
H.1 Defining Command-Line Argument
Command line arguments are a powerful way to pass parameters
to a program when it is executed on the system's command line.
the values of these arguments are passed on to your program
during program execution.
When a program starts execution without user interaction,
command-line arguments are used to pass values or files to it.
They allow users to customize the behavior of the program
without modifying its source code.
The function main can be defined either with no argument {void)
or with two arguments: one an integer and the other an array of
pointers to char (strings) that represent user-determined values to
be passed to main.
The number of elements in the array is stored in the first
argument. The pointers to the user values are stored in the array.
Although the names of the arguments are your choice,
traditionally they are called argc (argument count) and argv
(argument vector).
H.2 Using Command-Line Arguments
The argv array has several elements. The first element points
to the name of the program (its filename). It is provided
automatically by the program.
The last element contains NULL and may be used to identify
the end of the list.
The rest of the elements contain pointers to the user-entered
string values.
But what if our intent is to read a phrase? C looks at the user values as
strings.
SAMPLE PROGRAMS
ON
BITWISE OPERATORS AND ON MACROS
program to convert decimal to binary number system
OUTPUT:
Enter any number: 22
Converted binary : 00000000000000000000000000010110
#include <stdio.h>
#define INT_SIZE sizeof(int) * 8 /* Size of int in bits */
int main()
{
int num, index, i;
int bin[INT_SIZE];
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
index = INT_SIZE - 1;
while(index >= 0)
{
/* Store LSB of num to bin */
bin[index] = num & 1;
/* Decrement index */
index - -;
/* Right Shift num by 1 */
num >>= 1;
}
/* Print converted binary */
printf("Converted binary: ");
for(i=0; i<INT_SIZE; i++)
{
printf("%d", bin[i]);
}
return 0;
C program to count total of number of zeros and ones
in a binary number using bitwise operator
#include <stdio.h>
#define INT_SIZE sizeof(int) * 8 /* Total number of
bits in integer */
int main()
{
int num, zeros, ones, i;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
zeros = 0;
ones = 0;
for(i=0; i<INT_SIZE; i++)
{
/* If LSB is set then increment ones otherwise zeros */
if(num & 1)
ones++;
else
zeros++;
/* Right shift bits of num to one position */
num >>= 1;
}
printf("Total zero bit is %d\n", zeros);
printf("Total one bit is %d", ones);
return 0;
}
Output:
Enter any number: 22
Total zero bit is 29
Program to check Least Significant Bit (LSB) of a
number using bitwise operator
#include <stdio.h>
int main()
{
int num;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
/* If (num & 1) evaluates to 1 */
if(num & 1)
printf("LSB of %d is set (1).", num);
else
printf("LSB of %d is unset (0).", num);
return 0;
C program to check even or odd using bitwise
operator
#include <stdio.h>
int main()
{
int num;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
if(num & 1)
{
printf("%d is odd.", num);
}
else
{
printf("%d is even.", num);
}
return 0;
Program to swap two numbers
Suppose two integer values a and b
Perform, x = a ^ b
Now x ^ b will evaluate to a
and x ^ a will evaluate to b.
OUTPUT
Enter any two numbers: 25
65
Original value of num1 = 25
Original value of num2 = 65
Num1 after swapping = 65
Num2 after swapping = 25
#include <stdio.h>
int main()
{
int num1, num2;
/* Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
printf("Original value of num1 = %d\n", num1);
printf("Original value of num2 = %d\n", num2);
/* Swap two numbers */
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
printf("Num1 after swapping = %d\n", num1);
printf("Num2 after swapping = %d\n", num2);
return 0;
}
C program to count trailing zeros
in a binary number using bitwise
operator
/* Iterate over each bit of the
#include <stdio.h>
number */
#define INT_SIZE sizeof(int) * 8
for(i=0; i<INT_SIZE; i++)
/* Bits required to represent an {
integer */
/* If set bit is found the
int main()
terminate from loop*/
{ if((num >> i ) & 1)
int num, count, i; {
/* Input number from user */ /* Terminate from loop */
printf("Enter any number: "); break;
scanf("%d", &num); }
count = 0; /* Increment trailing zeros
/* Iterate over each bit of the count */
number */ count++;
}
printf("Total number of trailing
zeros in %d is %d.", num, count);
return 0;
OR
#include <stdio.h>
int main()
{
int num, count=0;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
while(!(num & 1))
{
count++;
num >>= 1;
}
printf("Total number of trailing zeros = %d.", count);
return 0;
}
OUTPUT
enter any number: 48
C program to count leading zeros in a
binary number using bitwise operator
#include <stdio.h> for(i=0; i<INT_SIZE; i++)
#define INT_SIZE sizeof(int) * 8 {
int main() // If leading set bit is found
{ if((num << i) & msb)
int num, count, msb, i; {
/* Input number from user */ /* Terminate the loop */
printf("Enter any number: "); break;
scanf("%d", &num); }
// Equivalent to count++;
// 10000000 00000000 00000000 }
00000000
printf("Total number of leading
msb = 1 << (INT_SIZE - 1); zeros in %d is %d", num, count);
count = 0; return 0;
/* Iterate over each bit */ }
INPUT/OUTPUT:
Enter any number: 22
Total number of leading zeros in 22 is 27