Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to C Programming CE00312-1 Lecture 8 Bitwise Operations.

Similar presentations


Presentation on theme: "Introduction to C Programming CE00312-1 Lecture 8 Bitwise Operations."— Presentation transcript:

1 Introduction to C Programming CE00312-1 Lecture 8 Bitwise Operations

2 Bitwise Operations - Introduction To date – logical operators AND&&(two ampersands) e.g. if ( x < y && y < z ) printf("x is less than z\n"); OR||(two vertical lines) e.g. if ( x < z || y < z ) printf(“x or y is less than z\n"); Now – manipulating individual bits.

3 Bitwise Complement The “~” operator Ones complement Inverts the individual bits in a number e.g.700000111 ~711111000 ~7-8 or ~7248 Depending upon number implementation

4 Two’s Complement ~number + 1 gives the “Twos Complement” of number. e.g.Twos complement of 7 700000111 ~11111000 ~ +111111001 -7 or 249 ???? Signed values careful when using bitwise operators!

5 Subtraction Easy to implement addition hardware. Subtraction hardware? Using two’s complement. can use adders to subtract. a – bis the same as a + (-b) -b acquired by taking one’s complement of b and adding 1 a + (~b + 1)

6 Bitwise Logical Operators & Bitwise AND |Bitwise INCLUSIVE OR ^Bitwise EXCLUSIVE OR These take two integer operands and manipulate them bit by bit - do not confuse them with && and ||

7 Bitwise Shift Operators Left Shift<< Usage expr1 << expr2; E.g.c = ‘Z’; c << 4; Right Shift>> Usage expr1 >> expr2;

8 Left Shifting 1248163264128 11100000= 7 0 1110000 11100000 11100000 11100000 = 14 = 28 = 112 = 56 = 224 = 192 ! 01110000 01100000 << 1

9 Shift Operators – Warning Operation of Left and Right are similar. They are not symmetrical Bits can be lost when shifting. Use on unsigned types Why? Value of expr2 should… not be negative not exceed number of bits in expr1

10 Precedence and Associativity If a=1; and b=2; What are the results of…… a > 1; a << 1+2 << 3; a + b > b;

11 Precedence and Associativity If a=1; and b=2; What are the results of…… a > 1;(a > 1; a << 1+2 << 3;(a << (1+2)) << 3 a + b > b; ((a + b) > b As with any operator – always check precedence and associativity.

12 Masks Masks are variables, or constants, that can be used to extract desired bits from a second variable. E.g – to check the state of the least significant bit int x = 7;int mask = 1; printf(“%d”, x & mask); consider (x & (1 << 2)) ? 1 : 0

13 Bit Fields Allows packing of data into a structure. Able to define the number of bits used for a variable Especially useful when… Memory or data storage at a premium Reading from non standard file formats – e.g 9 bit words C allows this within a structure by adding a bit length specifier after the variable.


Download ppt "Introduction to C Programming CE00312-1 Lecture 8 Bitwise Operations."

Similar presentations


Ads by Google