22.04.2015 Views

CS 3370 – Advanced C++ Programming Lab 4 – Bitwise Operations ...

CS 3370 – Advanced C++ Programming Lab 4 – Bitwise Operations ...

CS 3370 – Advanced C++ Programming Lab 4 – Bitwise Operations ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>CS</strong> <strong>3370</strong> – <strong>Advanced</strong> <strong>C++</strong> <strong>Programming</strong><br />

<strong>Lab</strong> 4 – <strong>Bitwise</strong> <strong>Operations</strong><br />

<strong>Bitwise</strong> operations are needed when processing bit flags in operating systems calls and when<br />

packing Boolean values into integers to conserve space. The bitwise operators are:<br />

> shift right<br />

| bitwise OR<br />

&<br />

bitwise AND<br />

^<br />

bitwise XOR (exclusive-or)<br />

~ bitwise NOT (flip all bits)<br />

These operators apply to integers and return new integer results. There are also associated<br />

assignment operators that modify their left operand: =, |=, &=, ^=, ~=.<br />

The shift operators take the integer to be processed as a left operand and the number of bit<br />

positions to shift as a right operand. The left operand is usually an unsigned integer, because a<br />

shift-right replicates the sign bit when processing a signed integer; with unsigned integers zeroes<br />

are introduced.<br />

To determine whether a particular bit is set or not, construct a mask, a like-sized integer with a 1<br />

in the position of interest and zeroes elsewhere. Then AND that mask with the original integer. If<br />

the result is non-zero, the bit is set. To illustrate, suppose we want to know if the bit in position 4<br />

is set in the integer n. Since bits are numbered right-to-left from 0, the needed mask is<br />

00000000000000000000000000010000<br />

This happens to be the hex integer 0x00000010, but we don’t need to know that, because we can<br />

construct the mask with the left-shift operator:<br />

unsigned int mask = 1u


The value for status is !!(32) = !(0) = 1. The logical-not operator (!) converts a non-zero to zero<br />

and a 0 to 1.<br />

To set a bit, OR the mask with the number:<br />

mask = 1u


Exercise<br />

Write a class named BitWord that holds an unsigned int and implements the following<br />

interface:<br />

class BitWord<br />

{<br />

public:<br />

explicit Bits(unsigned int n = 0);<br />

void set(size_t pos);<br />

void reset(size_t pos);<br />

void flip(size_t pos);<br />

bool test(size_t pos) const;<br />

unsigned int extract(size_t m, size_t n) const;<br />

operator unsigned int () const;<br />

friend ostream& operator

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!