bitwise operations

13

Upload: morna

Post on 25-Feb-2016

28 views

Category:

Documents


1 download

DESCRIPTION

Bitwise Operations. Who cares about bits?. Most people don’t! Operating systems do Embedded systems programming Flags, etc. People short on memory resources do, Can pack boolean values into an int Examples: std::bitset You do! Since Program 3 requires bitwise operations. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Bitwise Operations
Page 2: Bitwise Operations

Most people don’t! Operating systems do

Embedded systems programming Flags, etc.

People short on memory resources do, Can pack boolean values into an int Examples: std::bitset

You do! Since Program 3 requires bitwise

operations

Page 3: Bitwise Operations

Bitwise-OR (|) Bitwise-AND (&) Bitwise-XOR (^) (“exclusive-or”) Bitwise-NOT (~) Shift-left (<<) Shift-right (>>) Only work on integers

Any size (char, short, int, long) Unsigned integers should be used▪ To avoid sign extension with >> and integral

promotion

Page 4: Bitwise Operations

Test, set, reset, or flip (toggle) bits

Extract a subset of bits as a number

Page 5: Bitwise Operations

ANDing a bit with a 1 reads it (b & 1 == b) ORing a bit with 1 sets it to 1 (b | 1 == 1) ANDing a bit with 0 resets it (b & 0 == 0) XORing a bit with 1 flips it (b ^ 1 == ~b)

ORing a bit with 0 is a nop (b | 0 == b) ANDing a bit with 1 is a nop (b & 1 == b) XORing a bit with 0 is a nop (b ^ 0 == b)

Page 6: Bitwise Operations

First form a one-mask Place 1 in the desired bit position (n),

zeroes elsewhere: unsigned mask = 1u << n Note: bit-0 is on the far right (1’s place)

Then AND it with the number x & mask

The result is non-zero iff the bit is 1 To convert the result to 1 or 0: !!(x & mask)

Page 7: Bitwise Operations

OR the 1-mask into the number x |= mask

Page 8: Bitwise Operations

To set all bits: x = -1, or x = ~0u (preferred)

Mask to set the lower n bits: mask = (1u << n) – 1 (preferred), or mask = ~0u >> (NBITS – n)▪ NBITS is number bits in an int (= sizeof(int) *

CHAR_BIT) Mask to set bits m through n (inclusive, m

< n): mask = (1u << (n-m+1) – 1) << m

Page 9: Bitwise Operations

Form a 0-mask 0 in the bit position, 1’s elsewhere By flipping the 1-mask: unsigned mask = ~(1u << n)

Then AND into the number: x &= mask

Page 10: Bitwise Operations

Flip the corresponding masks for setting bits forming 0-masks

Then AND the mask into the number

Page 11: Bitwise Operations

If the desired value is 0, reset the bitOtherwise set itNo short-cut!

Page 12: Bitwise Operations

Form the appropriate 1-maskx ^= mask

Page 13: Bitwise Operations

Form the 1-mask to extract the bits By ANDing

Shift right the appropriate number of positions so the right-most bit of interest is in the

1’s placeExample: bitops.cpp

Extracts components of an IEEE float