bitwise operations
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 PresentationTRANSCRIPT
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
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
Test, set, reset, or flip (toggle) bits
Extract a subset of bits as a number
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)
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)
OR the 1-mask into the number x |= mask
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
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
Flip the corresponding masks for setting bits forming 0-masks
Then AND the mask into the number
If the desired value is 0, reset the bitOtherwise set itNo short-cut!
Form the appropriate 1-maskx ^= mask
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