Question
in C++ Define a class named Bits that holds a single integer variable. You will use this integer simply as a container of bits. The
in C++ Define a class named Bits that holds a single integer variable. You will use this integer simply as a container of bits. The number of bits you can support depends on the type of integer you use. We will use an unsigned long long, which on most platforms occupies 64 bits. However, DO NOT HARD-CODE the type of integer you use throughout your code. You should be able to change only one line of code for your class to work with a different size integer (see the using statement on the second code line below). The code skeleton below gets you started, and also shows you the interface your class needs to implement.
#ifndef BITS_H #define BITS_H #include#include #include class Bits { using IType = unsigned long long; enum {NBITS = sizeof(IType)*8}; IType bits = 0; // This is the only data in a Bits object public: Bits(IType n=0) { bits = n; } static int size() { return NBITS; } bool at(int pos) const { assert(0 <= pos && pos < NBITS); return bits & (IType(1) << pos); } void set(int pos) { assert(0 <= pos && pos < NBITS); // set the bit in position `pos` } void set() { bits = IType(-1); } void reset(int pos) { assert(0 <= pos && pos < NBITS); // return the bit in position `pos` } void reset() { bits = 0; } void assign(int pos, bool val) { assert(0 <= pos && pos < NBITS); // set or reset the bit in position `pos` } void assign(IType n) { bits = n; } void toggle(int pos) { assert(0 <= pos && pos < NBITS); // toggle the bit in position `pos` } void toggle() { bits = ~bits; } void shift(int n) { if (n > 0) // Shift right n else if (n < 0) // Shift left -n (n is negative, so -n is positive) // Ignore a 0-shift } void rotate(int n) { assert(abs(n) <= NBITS); if (n > 0) { // Rotate right } else if (n < 0) { // Rotate left (n is negative!) } } int ones() const { // Count the number of 1's // Let n = bits. // And the number with 1 // Then, shift n to the right, repeat... } int zeroes() const { return NBITS - ones(); } IType to_int() const { return bits; } friend bool operator==(const Bits& b1, const Bits& b2) { return b1.bits == b2.bits; } friend bool operator!=(const Bits& b1, const Bits& b2) { return b1.bits != b2.bits; } friend std::ostream& operator<<(std::ostream& os, const Bits& b) { return os << std::bitset (b.bits); } }; #endif
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started