C Session12

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Session 12

Bitwise Operators

l Bitwise Operators
l The One’s Complement
l File Inclusion
l C-ISAM
l Bit Fields
Bitwise Operators

I NTRODUCTION TO B ITWISE
O PERATORS
In this final session, we will study about the engineering
of binary digits or bits for short. When programs
interacting with the hardware is the need of the day,
bit manipulation is mandatory. Programming is
t INTRODUCTION TO
generally byte oriented and hardware is bit oriented.
BITWISE OPERATORS
Bit manipulation is possible only through the use of
t BITWISE OPERATORS: Operators. These Operators are used specifically to
AND, OR, XOR operate on Integers, Characters, Floats and Doubles.

t THE SHIFT
O PERATORS 7 6 5 4 3 2 1 0

t C-I SAM

t BIT FIELDS Character

8 7 6 5 4 3 2 1 0

Integer

The above tables show how bits are allocated to


characters and Integers.

The various Bitwise Operators used in C are:

& : Bitwise AND


| : Bitwise inclusive OR / XOR
^ : Bitwise exclusive OR
<< : Left shift
>> : Right shift
~ : one’s complement.

Comp-U-Learn
C Trim

B ITWISE O PERATORS : A ND , O R X OR
The Bitwise And Operator (&)

The bitwise AND Operator is the & symbol. This might be confused with the && logical AND
operator, although the usage of these two is almost identical. The & operator operates on two
operands. While Logical expressions return Zero or One, Bitwise expressions are capable of returning
Integers.

When the two binary numbers 1000 and 1101 are compared by making use of the bitwise &
operator, the first binary digit of the first number is compared with the first binary digit of the
second number.

If both are 1 then the first bit of the answer would be 1. If both the bits are not one, then the bit that
makes up the answer would be 0. Where 0 is encountered, the bit is turned off and where one is
encountered, it is turned on.

The following code shows the use of the Bitwise & applied on the numbers 60 and 13.

1. main()
2. {
3. unsigned int a = 60; /* 60 = 0011 1100 */
4. unsigned int b = 13; /* 13 = 0000 1101 */
5. unsigned int c = 0;
6. c = a & b; /* 12 = 0000 1100 */
7. }

The Truth table of &, shows what rules are applied in determining the resulting value.

0 & 0 = 0

0 & 1 = 0

1 & 0 = 0

1 & 1 = 1

The use of the & operator is mainly to determine whether a particular bit is on or off. It can also
be used in the case where the attributed byte,( the byte that is present in each and every 32-bit file
and whose value is governed by the individual bits) is to be checked.

Comp-U-Learn
Bitwise Operators

The Bitwise Inclusive OR (|)

This operator is mainly used to switch on a particular bit in a number. This is similar to the bitwise
AND operator, except that a bit of the result is a 1 if one or more of the corresponding bits is a 1.

The truth table for OR operator is:

0 | 0 = 0

0 | 1 = 1

1 | 0 = 1

1 | 1 = 1

Take the 110000100101. If we want to convert the third number from off to on, then applying the
rules from the table will generate the number 000010000000. Here all the other numbers are
turned off and the one number in question is turned on.

The following code shows how the | operator is used on the numbers 60 and 13.

1. main()
2. {
3. unsigned int a = 60; /* 60 = 0011 1100 */
4. unsigned int b = 13; /* 13 = 0000 1101 */
5. unsigned int c = 0;
7. c = a | b; /* 61 = 0011 1101 */
8. }

The Bitwise Exclusive OR/XOR

The first thing that strikes the mind is that there is no Logical counterpart for this Operator. Here,
the resulting bit is 1 if either, but not both, of the corresponding bits is 1. If both are 1 or both are 0,
the resulting bit is 0. This truth table says it all.

0 ^ 0 = 0
0 ^ 1 = 0
1 ^ 0 = 1
1 ^ 1 = 1

Comp-U-Learn
C Trim

A XOR operator is used to toggle a bit between on and off. It must be noted that if the XOR
operator is used between two numbers twice, then it returns the original number.

This bit of code shows how when XOR is used on the numbers 20 and 12.

1. main()
2. {
3. int One = 20;
4. int Two = 12;
5. printf(“One = %d Two = %d\n”, One, Two);
6. One ^= Two;
7. Two ^= One;
8. One ^= Two;
9. printf(“One = %d Two = %d\n”, One, Two);
10. }

The result would be, One is equal to 20 and Two is equal to 12. Then One is assigned the value of 12
and Two is assigned the value of 20

The Bitwise NOT Operator or One’s Complement Operator

This is an unary operator symbolized by ~. This Operator always precedes it’s operand. Which
would have to be an Integer type. It changes all 1’s to 0’s and vice versa. One’s compliment of
1100110011 will be 0011001100.

Usually, for a normal integer, on 16-bit machines, the maximum is 111111111111111 suppose we had
~ 000000000011111. The result would be 111111111100000 because we turn all 1’s into 0’s and vice
versa. We’ll leave you to figure out why ~ 000000000011111 equals 111111111111111 - 111111111100000.

Nothing much has to be explained about this operator as if a number is one, then it is ~0 and if a
number is zero then it is ~1.

The following lines show the relation.

NOT (1 AND 1) = 0

NOT (1 AND 0) = 1

Comp-U-Learn
Bitwise Operators

NOT (0 AND 1) = 1

NOT (0 AND 0) = 1

(1 OR 1) AND ( NOT (1 AND 1)) = 1 AND 0 = 0

(1 OR 0) AND ( NOT (1 AND 0)) = 1 AND 1 = 1

(0 OR 1) AND ( NOT (0 AND 1)) = 1 AND 1 = 1

(0 OR 0) AND ( NOT (0 AND 0)) = 0 AND 1 = 0

1 XOR 1 = 0

1 XOR 0 = 1

0 XOR 1 = 1

0 XOR 0 = 0

This example program should prove the point.

1. main()
2. {
3. int a,b;
4. for(a=0;a<=3;a++)
5. {
6. printf(“\n Decimal %d is same as binary”,a);
7. showbits(a);
8. b = ~a;
9. printf(“\n One’s compliment of %d is ”,a);
10. showbits(b);
11. }
12. }]
13.

The one’s compliment operator is sometimes referred to as the complementation operator too. It’s
associativity is from right to left.

Comp-U-Learn
C Trim

The Showbits()

Showbits()
{
int i,x,andmask;
for(i=15;i>=0;i—)
{
andmask = 1<i;
x = n&andmask;
x==0?printf(“0”):printf(“0”);
}}

The Output

T HE S HIFT O PERATORS
The need for shift operators arises when there is a need for multiplication or division of “2 to the
power of x”. Here two operands are worked on, the number to be shifted and the number of bits to
shift. The left operand is shifted left (<<) or right (>>) by the number of bit positions specified by the
right operand.

Integral promotions are performed on both operands, which must be of integral type. The result
type is promoted by the left operand. The right shift operator >> shifts the first operand to the right.

Comp-U-Learn
Bitwise Operators

The left shift operator << shifts the first operand to the left and zero fills the result in the right. Only
if the type of the left operand is unsigned type, then the >> operator zero fills the result on the left.
If the type of the left operand is signed type, then copies of the sign bit are shifted into the left bits
of the result.

In the following example the unsigned int Value and unsigned int Shift are the operands.

1. main()
2. {
3. unsigned int Value=4; /* 4 = 0000 0100 */
4. unsigned int Shift=2;
5. Value = Value << Shift; /* 16 = 0001 0000 */
6. Value <<= Shift; /* 64 = 0100 0000 */
7. printf(“%d\n”, Value); /* Prints 64 */
8. }

The above program makes use of the left shift operator.

The next program makes use of the >> operator.

1. main()
2. {
3. unsigned a = 0xf05a;
4. int b =a;
5. printf(“%u %d\n”,a,b);
6. printf(%x\n”, a>>6);
7. printf(%x\n”,b>>6);
8. }
The Output

Comp-U-Learn
C Trim

Here a represents an unsigned integer quality and b represents an integer. Both are initially
assigned the same value. When the extreme left bit contains a1, then b interprets this value as a
negative one.

It is to be noted that if the operand is a multiple of 2, then shifting it by one bit to the right is
similar to dividing it by 2.

C-ISAM
The Index of a book, makes it’s readers life more easy. Though indexes are not a part of the C
program , Indexes are necessary. ISAM is the abbreviation of “indexed sequential access method.
This is a method that deals with organizing the data in the files including indexes. The need for
ISAM arises when various sectors exist in a particular business or organization. To prevent various
mix-ups and eventual hazards, ISAM is applied.

C-ISAM

This might sound discouraging, but C does not have any readymade standard functions pertaining
to index manipulation. C – ISAM is a library of C functions that manages the indexed sequential
access method files. The entire relational database management system (RDBMS)is bypassed and
a direct access to record is allowed through the programmers’ applications. The standard advantages
of using C-ISAM is

quick data retrieval:


flexible indexing options;
data integrity;
ISAM system maintenance: Quick data retrieval: The B+ tree index architecture makes data
retrieval an exceptionally easy task. It makes use of index entries as keys that point to records. It
uses techniques that involve key compression for more efficient index storage and processing.

Flexible Indexing options: C-ISAM provides an option to create a large number of indexes for the
ISAM file. These can be derived from any one of the eight parts, which are made up of different
data types. Indexes can be built on multiple, single or individual parts of a field. Duplicate and
Unique key values are also supported.

Data Integrity : The transaction management and logging along with recovery features allow data
recovery quite easily. The concurrency of the data is managed by a locking mechanism. The integrity
of the indexes are protected by the Bcheck utility.

Comp-U-Learn
Bitwise Operators

System Maintenance: Built in routines, performs several maintenance tasks such as creation of
indexed file systems.

Add and delete indexes

Add, delete or modify records

Recorder data records

Rename and erase ISAM files

Lock records or files.

C-ISAM Datatypes: The data storage method employed here is machine independent.

Listed below are the C-ISAM data types and their counterparts in C

C-ISAM D A T A T Y P E C L ANGUAGE D ATATYPE


CHARTYPE char

INTTYPE int

LONGTYPE long

FLOATTYPE float

DOUBLETYPE double

DECIMALTYPE No equivalent

To use the function calls mentioned above, the isam.h header file has to be included.

B IT F IELDS
When a person employs C language to write code, he can use many features of the C language to
manipulate even the tiny bits of the memory space. Apart from the various operators, C language
also has a facility, where inclusion of variables less than eight bits in size, can also be included in
structures. These variables are termed as bit fields. The use of bit fields is to mainly enable better
memory utilization by storing data in the minimum number of bits required. Bit fields may be
declared from as less as one bit onwards.

Comp-U-Learn
C Trim

The general form for declaring a bit field is:

type name : number_of_bits;

What is to be remembered while using bit fields is that the members of a bit field should either be
declared as an int or an unsigned int.

In the following structure definition three unsigned variables are declared.

struct Membership
{
unsigned gender : 1;
unsigned scheme :2;
unsigned duration :3;
unsigned fees: 4;
};
The bit field is declared by following an unsigned int member name with a simple colon(:) and an
integer constant representing the width of the field, ie., the number of bits in which the member
is stored.

It is to be noted that a bit field member of a structure is accessed as any other structure member.

The following program shows how in a structure Membership, the gender of the member is stored
in 1 bit and the scheme of membership is stored in 2 bits. When the bit fields are established, they
can be referenced in the form of a regular structure element, as you will notice in line numbers 2-
9.

1. #include<stdio.h>
2. #define MALE 0;
3. #define FEMALE 1;
4. #define PERMANENT 0;
5. #define TEMPORARY 1;
6. #define FIVE 0;
7. #define TEN 1;
8. #define PAID 0;
9. #define UNPAID 1;
10. main()

Comp-U-Learn
Bitwise Operators

11. {
12. struct Membership
13. {
14. unsigned gender : 1;
15. unsigned scheme :2;
16. unsigned duration :3;
17. unsigned fee:4;
18. };
19. struct Membership m;
20. m.gender = MALE;
21. m.status = PERMANENT;
22. m.duration = TEN;
23. m.fee=PAID;
24. printf(“\n Gender = %d”, m.gender);
25. printf(“\n Status = %d”, m.status);
26. printf(“\n Duration = %d”, m.duration);
27. printf(“\n Fee = %d”, m.fee);
28. }

The Output

Comp-U-Learn
C Trim

Working with single bits and small groups of bits proves to be very useful. It must be remembered
that the mechanism for allocating memory to bit fields is governed by the rules and definitions of
the C language.Bit fields may be allotted from either the top or the bottom of the memory. If they
are unnamed bit fields, they can be used for padding.

To conclude, C bit fields are a convenient notation for the programmer. They are a means through
which a well defined compiler can generate efficient code.

URL S FOR B ITWISE OPERATORS

Extended Reference

http://www.lysator.liu.se/c/rat/title.html

T HE Z ERO H OUR
Q: What is the full form of ISAM?

Ans: ISAM stands for Indexed Sequential Access Method.

Q: What is the header file you need to use the ISAM function’s?

Ans: isam.h.

Q: What are the different types of bit wise operators?

Ans: One’s complement

Right shift

Left shift

Bitwise AND

Bitwise OR

Bitwise XOR or Exclusive OR

Comp-U-Learn
Bitwise Operators

Q: What is a bit field?

Ans: A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in size.

Q: Which symbol indicates the compiler that a bit field has been encountered?

Ans: The colon indicates the compiler that a bit field has been encountered.

T HE S ESSION G UIDE
The Session Guide helps you time your session with the help of the slides provided. Beneath each
image of the slides is the time given to be spent on each slide while it is being displayed. The slide
will thus, guide you through the contents of the session with ease.

Programming Usi

Bitwise Operators

Slide 1
Comp-U-Learn

Display Time

This slide discusses Bitwise operators in C. You should spend 5 minutes on introduction.

Comp-U-Learn
C Trim

Road Map

• Bitwise Operators • The Bitwsie OR


• The One’s • The Bitwsie XOR
Complement • File Inclusion
• The Right Shift • C - ISAM
Operator • Bit Fields
• The Left Shift
Operator
• The Bitwsie Amd
Slide 2
Comp-U-Learn

Display Time

You discuss the various points to be discussed in this session and you need to spend at least 10
minutes on this slide.

Bitwise Operators

⇒Bitwise operators operate on the bits that makeup data.

⇒Operating system,compilers,assemblers use bitwise operations.

⇒Operators can act on integers and characters.

7 6 5 4 3 2 1 0

Character

Integer

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Slide 3
Comp-U-Learn

Display Time

In this slide you will discuss about the Bit wise operators. Spend 10 minutes on this slide.

Comp-U-Learn
Bitwise Operators

Operations on Bitwise operators

Operator Operation
& Bitwise AND

| Bitwise Or

^ Bitwise XOR

<< Left Shift

>> Right Shift

~ One,s complement

Comp-U-Learn
Slide 4

Display Time

You will discuss the operations in the Bit wise operators. You can spend 15 minutes on this slide.

Types of Bitwise Operators

⇒ One’s Complement operator.

⇒ Right shift operator.

⇒ Left Shift operator.

⇒ Bitwise AND operator.

⇒ Bitwise OR operator

⇒ Bitwise XOR operator or Exclusive OR operator


Slide 5
Comp-U-Learn

Display Time

When you display this slide, you discuss the types of Bit wise operators. Keep this slide for 10
minutes.

Comp-U-Learn
C Trim

One’ Complement

⇒It is represented by ~
⇒Interchanges 0’s to 1’1 and vice versa.

Example:
j=45;
(it’s binary equivalent is 00101101
k=~j;
binary equivalent of k is 11010010.

Slide 6
Comp-U-Learn

Display Time

Spend 12 minutes on this slide as you will discuss the One’s complement when this slide is on
display.

Right Shift Operator

⇒It is represented by >>.


⇒Shifts bits to the right.
⇒Vacated space filled with zeros.
⇒No of places to shift can be specified.

Example
binary representation of x is 110010111.
Y=x>>1
binary representation of y is 01101011.

Slide 7
Comp-U-Learn

Display Time

You will discuss the right shift operator when you display this slide. Spend about 4 minutes on
this slide.

Comp-U-Learn
Bitwise Operators

The Left Shift Operator

⇒It is represented by <<.


⇒Shifts bits to the left.
⇒Vacated space filled with zeros.
⇒No. of bits shift can be specified.

Example
binary representation of x is 001001.
Y=x<<2.
Binary representation of y is 100100.

Slide 8
Comp-U-Learn

Display Time

You will discuss the left shift operator when you display this slide. Spend about 4 minutes on this
slide.

Bitwise AND

⇒It is represented by &.


⇒It operates on two operands.
⇒Both operands must be of same type.
⇒The result is based on the truth table.

Truth Table
Input 1 Input 2 Resultant
0 0 0
0 1 0
1 0 0
1 1 1

Slide 9
Comp-U-Learn

Display Time

Discuss the Bit wise AND operator when this slide is on the display for 5 minutes.

Comp-U-Learn
C Trim

Bitwise OR

⇒It is represented by |.
⇒It operates on two operands.
⇒Both operands must be of same type.
⇒The result is based on truth table.

Truth table
Input 1 Input 2 Resultant
0 0 0
0 1 1
1 0 1
1 1 1

Slide 10
Comp-U-Learn

Display Time

Discuss the Bit wise OR operator when this slide is on the display for 5 minutes.

Bitwise XOR or Exclusive OR

⇒It is represented by ^.
⇒It takes two operands.
⇒Both operands must be of same type.
⇒Result is based on truth table.

Truth table
Input 1 Input 2 Resultant
0 0 0
0 1 1
1 0 1
1 1 0
Slide 11
Comp-U-Learn

Display Time

When you display this slide, you discuss about the XOR operator. Spend nearly 10 minutes when
you display this slide.

Comp-U-Learn
Bitwise Operators

File Inclusion

⇒It is a preprocessor directive


⇒inserts contents of one file into another.
⇒Useful for gigantic programs.

Preprocessor command

#include “filename”
or
#include<filename>

Slide 12
Comp-U-Learn

Display Time

Spend about 8 minutes on this slide as you will discuss the file inclusion and it’s command.

The C-ISAM

⇒ISAM stands for Index Sequential Access Method.


ity:
nal
ctio
Fun
⇒Faster record lookup.
⇒Multiple indices.
⇒Transaction Handling.
⇒Compression of Key field.
⇒Duplication/Non Duplication of Key.
⇒File/record locking in multi user platform.

Comp-U-Learn
Slide 13

Display Time

You will discuss the C-ISAM and it’s functionality when this slide is displayed. Spend 8 minutes
with this slide.

Comp-U-Learn
C Trim

Bit fields

⇒Set of adjacent bits.


⇒Size varies from 1 to 16.
⇒Name and size can be defined by structure.

General format

S t r u ct t ag - n am e
{
d a t a t y p e n a me 1 : bi t l en g th ;
d a t a t y p e n a me 2 : bi t le n gt h ;
}

Slide 14
Comp-U-Learn

Display Time

Discuss about the Bit fields and it’s format for 10 minutes when this slide is displayed.

Going Over it Again

• Bitwise operators operate on the bit that makeup data


• And ,OR,Left Shift,Right Shift,Xor, One’s complement are
birwise operators
• One’s Complement operator is represented by ~
• Bitwise Right shift operator is represented by >>.
• Bitwise left shift operator is represented by <<.
• Bitwise XOR opertor is represented by ^.
• Bitwise OR operotor is represented by |.
• Bitwise And operotor is represented by &

Slide 15
Comp-U-Learn

Display Time

This slide shows the going over it again. You summarize all the points that are covered in this
session and can spend 4 minutes on this slide.

Comp-U-Learn

You might also like