Docsity

Bit Operators, Logical Operators - Introduction to Programming - Lecture Slides, Slides of Computer Programming

Partial preview of the text

Download Bit Operators, Logical Operators - Introduction to Programming - Lecture Slides and more Slides Computer Programming in PDF only on Docsity!

Introduction to Programming

Lecture 21

Today’s Lecture

 Bit manipulation

 Bit operators

Bit manipulation operators

& Bitwise AND Operator

| Bitwise OR Operator

^ Bitwise Exclusive OR Operator

~ NOT Operator

<< Left Shift Operator

Right Shift Operator

Bitwise AND Operator

Truth table for AND operation

Bit1 Bit2 Bit1 & B it 1 1 1 1 0 0 0 1 0 0 0 0

Example

#include <iostream.h> main ( ) { int number = 12 ; if ( number & 0x8 ) cout << "Bit number four is set" << endl ; else cout << "Bit number four is not set" << endl ; }

Bitwise OR Operator

Truth table for OR operation A B A|B 1 1 1 1 0 1 0 1 1 0 0 0

Bitwise OR Operator

Example 2

x = 8 | 1

1 0 0 0 0 0 0 1


1 0 0 1

Hence the result x = 9

Bitwise Exclusive OR Operator

Truth table for Exclusive OR operation

A B A^B 1 1 0 1 0 1 0 1 1 0 0 0

NOT Operator

Truth table for NOT operator

A ~A 0 1 1 0

NOT Operator

x = 8

~ ( 1000 ) = 0111

= 7

Read Write And

Execute

Exclusive OR Operator

Example

unsigned int a , b , c ; a = 112 ; b = 32 ; c = a ^ b ; c = ( a ^ b ) ^ b ; the result is a c = ( a ^ b ) ^ a ; the result is b

Hot Plug

Example

Swapping two integers without a temporary storage

unsigned int a = 12 ; unsigned int b = 8 ;

a = a ^ b ; b = b ^ a ; a = a ^ b ;