Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Bit Operations By C. Shing ITEC Dept Radford University.

Similar presentations


Presentation on theme: "Chapter 8 Bit Operations By C. Shing ITEC Dept Radford University."— Presentation transcript:

1 Chapter 8 Bit Operations By C. Shing ITEC Dept Radford University

2 Slide 2 Objectives Understand how to use bit operators Understand how to use mask Understand how to pack and unpack characters

3 Slide 3 Bit Operators OperatorExplain (bitwise) ~complement &And |Or ^Exclusive or <<Left shift >>Right shift

4 Slide 4 Bit Operators Use unsigned type involving > Signed type that shifts sign bit is system dependent

5 Slide 5 Example: unsigned int a=23, b=33; char c=‘C’;

6 Slide 6 Example: Expres sion Result a00000000 00000000 00000000 00010101 b00000000 00000000 00000000 00100001 ~a11111111 11111111 11111111 11101010 a&b00000000 00000000 00000000 00000001 a|b00000000 00000000 00000000 00110101 a^b00000000 00000000 00000000 00110100

7 Slide 7 Example: (Cont.) Expres sion Result c00000000 00000000 00000000 01000011 c<<500000000 00000000 00001000 01100000 c>>300000000 00000000 00000000 00001000

8 Slide 8 Mask Constant or variable to extract desired bits Bit mask: extract 1 bit Byte mask: extract 1 byte

9 Slide 9 Bit Mask Example: int i, j, n, mask=1; n=…; for (i=0;n >= j && i<32;++i) { printf(“%d”,n&mask?1:0); j*=2; // use j to get rid of leading 0’s in binary rep. mask <<=1; }

10 Slide 10 Byte Mask Example: int i, mask=255; int n; n=…; for (i=0;i<4;++i) { printf(“%c”,n&mask?’1’:’0’); mask <<=8; }

11 Slide 11 Binary Representation Example: find binary representation offind binary representation of a positive integer

12 Slide 12 Data Compression pack: Save space Save time: process 32 bits at a time instead of 1 character unpack

13 Slide 13 Data Compression – pack Example: int pack4char (char char1, char char2, char char3, char char4) { int a=char1; return (((a <<8)|char2)<<8|char3)<<8|char4; }

14 Slide 14 Data Compression – unpack Example: int i, m; m=…; for (i=0; i<4;++i) unpackint(m, i); int unpackint (int m, int n) { int i=8*n; unsigned mask=255; mask <<=i; return (m&mask)>>i; }

15 Slide 15 Practice Given unsigned a=1, b=2; Find the values of the following table: Expression Value ________ _____ a >1 a<<1+2 <<3 a+b >b

16 Slide 16 Practice (Answer) Given unsigned a=1, b=2; Find the values of the following table: Expression Value ________ _____ a >1 2 a<<1+2 <<3 64 a+b >b 3072

17 Slide 17 References Deitel & Deitel: C How to Program, 4th ed., Chapter 10, Prentice Hall


Download ppt "Chapter 8 Bit Operations By C. Shing ITEC Dept Radford University."

Similar presentations


Ads by Google