Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views20 pages

File 7

ekwjfk pokepew opkpokop f wojoej fwojfp ewop

Uploaded by

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

File 7

ekwjfk pokepew opkpokop f wojoej fwojfp ewop

Uploaded by

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

Subject Name Logical Thinking & Problem Solving

Subject Code 25CSH-107


Semester 1

LESSON-8 BITWISE OPERATORS AND TYPE CONVERSION


LESSON OBJECTIVES

• To learn in detail about bitwise operators, their working and applications


STRUCTURE OF THE LESSON

• Why Bitwise operators


• Types of Bitwise Operators
• Type Casting
• Summary
• FAQs
• References
1. Why Bitwise Operators?

Bitwise operators are most useful operators as they are used significantly in encryption and
decryption and writing more optimised functions in a program. Before beginning our
journey with bitwise operator, let’s have a look at the this beautiful video explaining
“WHAT ARE BITES AND BYTES”

https://youtu.be/AdF2uk-EscE

1|Page
1.1 Introduction

In arithmetic-logic unit (which is within the CPU), mathematical operations like: addition,
subtraction, multiplication and division are done in bit-level. To perform bit-level operations in
C programming, bitwise operators are used.

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 & (bitwise AND), | (bitwise
OR), ~ (bitwise NOT), ^ (XOR), << (left shift) and >> (right shift).

X Y x|y x&y x^y


0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0
Table1: Truth table of Bitwise operations

1.2 Types of Bitwise Operator


We have 6 types of bitwise operators whose details and description are discussed below:

Operator Meaning of operator


& Bitwise And
| Bitwise Or
^ Bitwise XOR
~ Bitwise Compliment
<< Left Shift
>> Right Shift
Table2: Bitwise Operators

1.2.1 Bitwise AND operator &

The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an
operand is 0, the result of corresponding bit is evaluated to 0.Let us suppose the bitwise AND
operation of two integers 12 and 25.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bit Operation of 12 and 25

00001100

&00011001

00001000 = 8 (In decimal)

Example1: Bitwise AND

2|Page
#include <stdio.h>

int main()

int a = 12, b = 25;

printf("Output = %d", a&b);

return 0;

Output

Output = 8

1.2.2 Bitwise OR operator |

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C


Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100

| 00011001

00011101 = 29 (In decimal)

Example 2: Bitwise OR

#include <stdio.h>

int main()

int a = 12, b = 25;

printf("Output = %d", a|b);

return 0;

3|Page
}

Output

Output = 29

1.2.3 Bitwise XOR (exclusive OR) operator ^

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It
is denoted by ^.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25

00001100

^ 00011001

________

00010101 = 21 (In decimal)

Example 3: Bitwise XOR

#include <stdio.h>

int main()

int a = 12, b = 25;

printf("Output = %d", a^b);

return 0;

Output

Output = 21

1.2.4 Bitwise complement operator ~

Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0
and 0 to 1. It is denoted by ~.

4|Page
35 = 00100011 (In Binary)

Bitwise complement Operation of 35

~ 00100011

________

11011100 = 220 (In decimal)

Twist in bitwise complement operator in C Programming

The bitwise complement of 35 (~35) is -36 instead of 220, but why?

For any integer n, bitwise complement of n will be -(n+1). To understand this, you should have
the knowledge of 2's complement.

2's Complement

Two's complement is an operation on binary numbers. The 2's complement of a number is equal
to the complement of that number plus 1. For example:

Decimal Binary 2's complement

0 00000000 -(11111111+1) = -00000000 = -0(decimal)

1 00000001 -(11111110+1) = -11111111 = -256(decimal)

12 00001100 -(11110011+1) = -11110100 = -244(decimal)

220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Table 1: 2’s complement

Remember overflow is ignored while computing 2's complement.

The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the
output is -36 instead of 220.

Bitwise complement of any number N is -(N+1). Here's how:

Bitwise complement of N = ~N (represented in 2's complement form)

2'complement of ~N= -(~(~N)+1) = -(N+1)

Example 4: Bitwise complement

#include <stdio.h>

5|Page
int main()

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

printf("Output = %d\n",~-12);

return 0;

Output

Output = -36

Output = 11

1.2.5 Shift Operators in C programming

There are two shift operators in C programming:

Right shift operator

Left shift operator.

1.2.5.1 Right Shift Operator

Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted
by >>.

212 = 11010100 (In binary)

212>>2 = 00110101 (In binary) [Right shift by two bits]

212>>7 = 00000001 (In binary)

212>>8 = 00000000

212>>0 = 11010100 (No Shift)

1.2.5.2 Left Shift Operator

Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by
<<.

212 = 11010100 (In binary)

212<<1 = 110101000 (In binary) [Left shift by one bit]

6|Page
212<<0 =11010100 (Shift by 0)

212<<4 = 110101000000 (In binary) =3392(In decimal)

Example 5: Shift Operators

#include <stdio.h>

int main()

int num=212, i;

for (i=0; i<=2; ++i)

printf("Right shift by %d: %d\n", i, num>>i);

printf("\n");

for (i=0; i<=2; ++i)

printf("Left shift by %d: %d\n", i, num<<i);

return 0;

Right Shift by 0: 212

Right Shift by 1: 106

Right Shift by 2: 53

Left Shift by 0: 212

Left Shift by 1: 424

Left Shift by 2: 848

2. Type Casting/ TypeConversion in C

The type conversion process in C is basically converting one type of data type to other to
perform some operation. The conversion is done only between those datatypes wherein the
conversion is possible ex – char to int and vice versa.

2.1 Implicit Type Conversion

7|Page
This type of conversion is usually performed by the compiler when necessary without any
commands by the user. Thus it is also called "Automatic Type Conversion".

The compiler usually performs this type of conversion when a particular expression contains
more than one data type. In such cases either type promotion or demotion takes place.

Keep in mind certain rules:

1. char or short type operands will be converted to int during an operation and the outcome
data type will also be int.
2. If an operand of type long double is present in the expression, then the corresponding
operand will also be converted to long double same for the double data type.
3. If an operand of float type is present then the corresponding operand in the expression
will also be converted to float type and the final result will also be float type.
4. If an operand of unsigned long int is present then the other operand will be converted to
unsigned long int and the final result will also be unsigned long int.
5. If an operand of long int is present then the other operand will be converted to long int
and the final result will also be long int.
6. If an operand of unsigned int is present then the other operand will be converted to
unsigned int and the final result will also be unsigned int.

Figure1: Implicit type conversion

8|Page
Now, let’s focus on some examples to further understand about type conversions in C.

Example 1

int a = 20;

double b = 20.5;

a + b;

Here, first operand is int type and other is of type double. So, as per rule 2, the variable a will be
converted to double. Therefore, the final answer is double a + b = 40.500000.

Example 2

char ch='a';

int a =13;

a + c;

Here, first operand is char type and other is of type int. So, as per rule 1, the char variable will be
converted to int type during the operation and the final answer will be of type int. We know the
ASCII value for ch is 97. Therefore, final answer is a + c = 97 + 13 = 110.

Example 3

char ch='A';

unsigned int a =60;

a * b;

Here, the first operand is char type and the other is of type unsigned int. So, as per rule 6, char
data type will be converted to unsigned int during the operation. Therefore, the final result will
be an unsigned int variable, 65 + 60 = 125.

Thus, all these above illustrations suggest that whenever the compiler deals with different data
types in an expression, the operand which is present at the lower rank will be converted to the
corresponding datatype of the operand with the higher rank.

For ease of understanding follow the flowchart given below, in which datatypes have been
arranged in a hierarchy of highest to the lowest rank.

2.2 Explicit Type Conversion

9|Page
Explicit type conversion rules out the use of compiler for converting one data type to another
instead the user explicitly defines within the program the datatype of the operands in the
expression.

Figure2: Explicit type conversion

The example below illustrates how explicit conversion is done by the user.

Example:

double da = 4.5;

double db = 4.6;

double dc = 4.9;

//explicitly defined by user

int result = (int)da + (int)db + (int)dc;

printf("result = %d", result);

Output

result = 12

Thus, in the above example we find that the output result is 12 because in the result expression
the user has explicitly defined the operands (variables) as integer data type. Hence, there is no
implicit conversion of data type by the compiler.

If in case implicit conversion was used the result would be 13.

10 | P a g e
FAQ’S
Q1. Compute the sign of an integer?

The MSB bit of a number defines their sign. If the MSB bit is set, the number will be negative.

#include <stdio.h>

int main()

int sign = 0;

int data = 0;

printf("Enter the number\n");

scanf("%d",&data); //Get the number

sign = (data > 0) - (data < 0); // check the sign of the number

if(sign == 1)

printf("Enter number is a positve number\n");

else if(sign == -1)

printf("Enter number is a negative number\n");

else

printf("Enter number is zero\n");

return 0;

11 | P a g e
Q2. Detect if two integers have opposite signs?

The two integers have the different signs if their MSB (bit) is different. In “C” Language using
the EX-OR operator, we can check the sign of the integers.

We know that for the same input EX-OR produces the low output and for the different input it
produces the high output.

E.g.

BIT1 BIT2 BIT1 ^ BIT2

1 1 0

0 0 0

1 0 1

0 1 1

Let the given integers are “a” and “b”. The EX-OR of sign bit (MSB) of “a” and “b” will be 1 if
the MSB of “a” and “b” is different. In other words, we can say, EX-OR of “a” and “b” will be
negative if “a” and “b” have the opposite signs.

#include<stdbool.h>

#include<stdio.h>

bool CheckOppositeSign(int a, int b)

bool bRetValue = 0;

bRetValue = ((a ^ b) < 0); // 1 if a and b have opposite signs

return bRetValue;

int main()

int a = 0,b=0;

bool bRetValue;

//ENTER THE VALUE OF a & b

12 | P a g e
printf("Enter the Value of a = ");

scanf("%d",&a);

printf("\nEnter the Value of b = ");

scanf("%d",&b);

bRetValue = CheckOppositeSign(a, b); // check signs of a & b

if (true == bRetValue)

printf ("\nIntegers have the opposite sign\n\n");

else

printf ("\nInteger have the same sign\n\n");

return 0;

Q3. Write a program to check an integer is a power of 2?

Here, I am writing a small algorithm to check the power of 2. If a number is a power of 2, the
flag will be 1.

#include <stdio.h>

int main()

int flag = 0;

int data = 0;

printf("Enter the number ");

scanf("%d",&data); //Get the number

13 | P a g e
flag = ((data != 0) && !(data & (data - 1))); // check the power of 2

if(flag == 1)

printf("Number is a power of 2 \n");

else

printf("Enter number is not power of 2 \n");

return 0;

Here assumption is the bit of register starts with 0th position, it means the 2nd position is
actually 3rd bits.

D7 D6 D5 D4 D3 D2 D1 D0

Q4. How to set a particular bit in C?

Setting a Bits

Bitwise OR operator (|) use to set a bit of integral data type.”OR” of two bits is always one if any
one of them is one.

An algorithm to set the bits

Number | = (1<< nth Position)

A simple program to set a bit:

#include <stdio.h>

int main(int argc, char *argv[])

unsigned char cData=0x00;

int iPos =0;

14 | P a g e
printf("cData = 0x%x\n\n",cData);

printf("Enter the position which you want set = ");

scanf("%d",&iPos);

//Set the nth bit.

cData|=1<<iPos;

//Print the data

printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);

return 0;

Q5. When should a type cast not be used?

Ans. A type cast can be used to change the data from one type to another type. For example, it
can be used to change the data from double data

type to integer data type. But it cannot be used to convert integer data type to double data type.
In other words, we can say that type cast can be

used to convert larger data types to smaller data types. But note it that it cannot convert smaller
data types to larger data types. Doing this will

give an error.

Also, type cast cannot be used to override constant. Overriding constants can cause runtime
errors

For eg. #include

#include

main()

double a=6.567;

clrscr();

int b=(double)a;

printf("%d",a);

15 | P a g e
printf("%d",b);

getch();

The output will be: 6.567

16 | P a g e
ASSESSMENT TEST

Q1. WAP to clear a bit.

Q2.We define S to be a sequence of distinct sequential integers from 1 to n ; in other words

S={1,2,3,….n}, . We want to know the maximum bitwise AND value of any two integers, a

and b (where a<b ), in sequence S that is also less than a given integer, k .

Complete the function in the editor so that given n and k , it returns the maximum a&b<k .

Note: The &symbol represents the bitwise AND operator.

Sample Input 0

3
52
85
22
Sample Output 0

1
4
0
Write the code of the above scenario that satisfies the above situation.

Q3. What will be the output of the C program?

#include<stdio.h>

int main()

int a = 4, b = 2;

printf("a^b = %d", a^b);

return 0;

17 | P a g e
A. 12

B. 10

C. 8

D. 6

Q4. What will be the output of the C program?

#include<stdio.h>

int main()

int a = 4, b = 2;

printf("a^b = %d", a^b);

return 0;

A. 12

B. 10

C. 8

D. 6

Q5. [&] is the symbol of bitwise And.

Q6. [float to char pointer] type of conversion is NOT accepted?

18 | P a g e
SUMMARY

In this lecture we have learnt a large bitwise operators supported by C language. We have learnt
how to use C bitwise operators to perform various kind of operations. Apart from Bitwise
operators Typecasting is also discussed which is also known as type conversion means
converting one data type into another.’C' provides an implicit and explicit way of type
conversion.Implicit type conversion operates automatically when the compatible data type is
found.Explicit type conversion requires a type casting operator.

Keep in mind the following rules for programming practice when dealing with different data type
to prevent from data loss :

• Integers types should be converted to float.


• Float types should be converted to double.
• Character types should be converted to integer.

19 | P a g e
REFERENCES AND LINKS

References and Links:

1 Books Programming in C by Reema Thareja.


2 Books Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
3 Books The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.
4 Books Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.

5 Weblink https://www.tutorialspoint.com/cprogramming/c_operators.htm

6 Weblink https://www.programiz.com/c-programming
7 Weblink https://fresh2refresh.com/c-programming/

8 Weblink https://www.studytonight.com/c/

9 Weblink https://www.javatpoint.com/c-operators

10 Video https://www.youtube.com/watch?v=MyxVAq9MifI
link
11 Video https://www.youtube.com/watch?v=xXBitioUzf8
link
12 Online https://www.coursera.org/
course
link
13 Online https://www.udemy.com/
course
link
14 Online https://www.niit.com/
course
link

20 | P a g e

You might also like