Programming for Engineers Bit Manipulation ICEN 200– Spring 2018 Prof. Dola Saha 1
Bitwise Operation Ø Computers represent all data internally as sequences of bits. Ø Each bit can assume the value 0 or the value 1. Ø The bitwise operators are used to manipulate the bits of integral operands both signed and unsigned. Ø Unsigned integers are normally used with the bitwise operators. Ø Bitwise manipulations are machine dependent. 2
Bitwise Operator 3
Bitwise Operation Example n=13 00001101 ~n 11110010 00001101 n << 1 00011010 Lost 0 0 Inserted 00001101 n << 3 Lost Inserted 01101000 three 0s three 0’s 00001101 n >> 3 Inserted 00000001 101 Lost three 0s 4
Bitwise Operation Example n 00001101 m 01010101 n&m 00000101 00001101 n m 01010101 n|m 01011101 00001101 n m 01010101 n^m 01011000 5
Bit Order Ø Most Significant Bit (MSB) Ø Least Significant Bit (LSB) 01001001 LSB MSB 6
Field Extraction: Mask Ø ANDing a bit with 0 produces 0. Ø ANDing a bit with 1 produces the original bit. 01001101 Data 01001101 Only rightmost two bits needed 01001101 Data & 00000011 Mask = 00000001 Result 7
Field Extraction: Mask and Shift 01001001 Data 2 nd & 3 rd bits needed 01001101 01001001 Data & Mask 00001100 = 00001000 >> 2 00000010 Result 8
Field Insertion 00000001 Flag1 01 10 Flag2 Flag1 & b 6 b 7 b 4 b 5 Mask 00000011 00001001 Data = Make sure that you have 00000001 only two bits in Flag1 << 6 01000000 Shifted | Data 00001001 = 01001001 9
Flip bits 01001001 Data Flip 2 nd & 3 rd bits 01000101 01001001 Data ^ Mask 00001100 = 01000101 10
Display Bits Example (1) 11
Display Bits Example (2) 12
Bitwise Operation Example Code (1) 13
Bitwise Operation Example Code (2) 14
Bitwise Operation Example Code (3) 15
Bitwise Operation Example Code (4) 16
Bitwise Operation Example Code Output 17
Bitwise Operation Application: TCP segment structure 32 bits URG: urgent data counting source port # dest port # (generally not used) by bytes sequence number of data ACK: ACK # (not segments!) acknowledgement number valid head not receive window U A P R S F PSH: push data now Len (4) used # bytes (generally not used) checksum Urg data pointer rcvr willing to accept RST, SYN, FIN: options (variable length) connection estab (setup, teardown commands) application data Internet (variable length) checksum (as in UDP) 18
Multiply and Divide by Bitwise Operation Ø Left Shift § Multiply 2 3 2 2 2 1 2 0 positional powers of 2: 2 4 decimal positional value: 16 8 4 2 1 binary number: 0 0 1 1 1 4 + 2 + 1 = 7 10 Left shift: 0 1 1 1 0 8 + 4 + 2 = 14 10 Ø Right Shift (without rotate) § Divide 19
Multiplication using shift x * 10 Ø § x * 10 = x * (8 + 2) = (x * 8) + (x * 2) = (x * 2 3 ) + (x * 2 1 ) = (x << 3) + (x << 1) x * 20 Ø § x * 20 = x * (16 + 4) = (x * 16) + (x * 4) = (x * 2 4 ) + (x * 2 2 ) = (x << 4) + (x << 2) x * 15 Ø § x * 15 = x * (16 - 1) = (x * 16) - x = (x * 2 4 ) - x = (x << 4) - x 20
Recommend
More recommend