0% found this document useful (0 votes)
22 views60 pages

GAT - Bitwise Operator - Updated

Uploaded by

wm27zfcpwv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views60 pages

GAT - Bitwise Operator - Updated

Uploaded by

wm27zfcpwv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Module 5

BIT WISE OPERATOR


Bitwise operators
There are six bitwise operators:
 bitwise AND (&)
 bitwise OR (|)
 bitwise XOR (^)
 bitwise complement (~)
 left shift (<<)
 right shift (>>)
 Rotation
Bitwise AND (&)
#include<stdio.h>  If the corresponding bit positions in
void main() both the operands are 1 , then AND
operation results in 1, otherwise
{ AND operation results in 0.
int a,b,c;  0 & 0 =0
a=10;  0 & 1 =0
b=6;  1 & 0 =0
c=a&b;  1 & 1 =1
printf(“%d &%d=%d\n”, a,b,
c);
}

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 )

 The parameter list in the macro definition can Be empty.


For example, most C implementations use a macro to
define the getchar function from the getc function:

#define getchar ( ) getc (stdin)


Nested Macros
 It is possible to nest macros. C handles nested macros by
simply rescanning a line after macro expansion.
 Therefore, if an expansion results in a new statement with
a macro, the second macro will be properly expanded.
 #define PRODUCT(a, b) (a) * (b)
 #define SQUARE(a) PRODUCT ( a , a )
 The expansion of x = SQUARE ( 5 ) ;
 results in the following expansion: x = PRODUCT(5, 5)
 which after rescanning becomes x = (5) * (5);
Undefining Macros
 Once defined, a macro command cannot be redefined.
 Any attempt to redefine it will result in a compilation error.
 However, it is possible to redefine a macro by first undefining it, using
the #undef command and defining it again:
 #define SIZE 10
 #undef SIZE
 #define SIZE 20
Predefined Macros
Operators Related to Macros
 1. String Converting Operator (#)
 The string converting operator ( #) is a macro operation that
converts a formal parameter into a string surrounded by
quotes.
#define PRINT_VAL(a) printf(#a , as shown in » contains: %d\n", (a))
 When called in a program
 PRINT_VAL (amt);
 the preprocessor expands the macro to
 printf ("amt" "contains: %d\n" / amt);
 preprocessor automatically concatenates two string literals
into one string
 printf ("amt contains: %d\n", amt);
Merge Operator (##)
 it may he necessary to write macros that generate new tokens.
 With the merge command operator, two tokens are combined.
 For example, imagine we want to create Al, B3, and Z8 in our
program.
 #define FORM(T, N) T##N
 Now ii we use the following code:
 int FORM (A, 1) = 1;
 float FORM (B, 3) = 1.1;
 char FORM (Z, 8) = 'A’;
 we get
 int Al = 1;
 float B3 = 1.1;
 char Z8 = 'A';
G.3 Conditional Compilation
 The third use of the preprocessor commands is conditional
compilation.
 Conditional compilation allows us to control the
compilation process by including or excluding statements.
 The defined Operator
 The defined operator can be used only in a conditional
compilation it cannot be used in macros. The value of
defined (macro-name ) is 0 if the name is not defined and 1
if it is defined. For example, after
 #define PI 3.14
 The value of defined ( PI ) is 1 and the value of
! defined ( PI ) is 0.
Two-Way Commands
 The two-way command tells the preprocessor to select
between two choices.
 The # if part or the else part can be empty.
 EXAMPLE 1. Let us see how a conditional command can help us
in program development. Imagine we need to include a very large
file in our program.
 #if 0
 #include "large.h"
 #endif

 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

You might also like