Bit Manipulation
Manipulating bits is a very common task in embedded systems.
Unfortunately, most
high-level programming languages don't support operations on individual bits.
In order to manipulate bits in high-level languages, bitwise logic operators
must be used. In this lab, you will use these bitwise operators to perform
several bit manipulation tasks.
-
Download the provided code (
bitmanip.h,
bitmanip.cc,
main.cc,
Makefile)
-
The file bitmanip.cc contains empty function definitions for all of the
bit manipulation tasks you will be implementing.
-
Implement the following function in bitmanip.cc:
-
void printBinary( unsigned long bits ) - This function prints a binary
representation of the unsigned long specified by bits.
-
unsigned long clearBit( unsigned long bits, unsigned short bit ) - This
function clears a bit specified by "bit" in the unsigned long "bits".
-
unsigned long setBit( unsigned long bits, unsigned short bit ) - This
function sets a bit specified by "bit" in the unsigned long "bits".
-
unsigned long changeBit( unsigned long bits, unsigned short bit,
unsigned short value ) - This
function changes a bit specified by "bit" in the unsigned long "bits" to the
value specified by "value".
-
unsigned long getBit( unsigned long bits, unsigned short bit) - This function
return either a 0 or 1 depending on the value of the bit specified by "bit"
in the unsigned long "bits".
-
unsigned short countOnes( unsigned long bits ) - This function returns the
amount of bits that have a value of 1.
-
unsigned long rotateLeft( unsigned long bits, unsigned short amount ) -
This function rotates the parameter "bits" to the left by the amount specified
by "amount".
-
unsigned long brev( unsigned long bits ) - This function reverses the bits
of the "bits" parameter.
-
Use the following C++ operators:
-
& (bitwise and)
-
| (bitwise or)
-
^ (bitwise xor)
-
~ (bitwise invert)
-
Add at least 10 test cases for each function to the main.cc file. Make
sure to use asserts for each test case. Several example test cases are
provided.
-
Compile and test your code on hill.cs.ucr.edu. Use the provided Makefile.
-
Once you have all the test cases completed, have the TA check you out and
turn in your code online.
-
Useful logic operations:
-
XORing a bit with 1 inverts the bit
-
ANDing a bit with 0 clears the bit
-
ORing a bit with 1 sets the bit