This C++ Program demonstrates the implementation of Bit Array.
Here is source code of the C++ Program to demonstrate the implementation of Bit Array. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/** C++ Program to Implement Bit Array*/#include <iostream>#include <string>using namespace std;
#define BIT_ARRAY_LENGTH 4typedef struct
{unsigned int bit : 1;
} Bit;
/** Bit Array Class*/class BitArray{private:
Bit **bitValues;
public:
BitArray()
{bitValues = new Bit* [BIT_ARRAY_LENGTH];
}/** Return Bit at a position*/Bit *getBit(int value,int position)
{Bit *singleBit = new Bit;
singleBit->bit = 0;
if(position == 0)
{singleBit->bit = value & 1;
}else{singleBit->bit = ( value & (1 << position ) ) >> position;
}return singleBit;
}/** Set Bit at a position*/BitArray *setBit(BitArray *bt,Bit *bit,int position)
{bt->bitValues[position] = bit;
return bt;
}/** Return value of a bit array*/int getValue(BitArray *bitArray)
{int value = 0;
unsigned int bitValue = 0;
bitValue = bitArray->bitValues[0]->bit;
value |= bitValue;
for(int i = 1; i < BIT_ARRAY_LENGTH; i++)
{bitValue = bitArray->bitValues[i]->bit;
bitValue <<= i;
value |= bitValue;
}return value;
}};
/** Main*/int main()
{int val;
cout<<"Enter 4 bit integer value(0 - 8): ";
cin>>val;
BitArray bt, *samplebt;
samplebt = new BitArray;
for (int i = 0; i < BIT_ARRAY_LENGTH; i++)
{samplebt = bt.setBit(samplebt, bt.getBit(val, i), i);
cout<<"Bit of "<<val<<" at positon "<<i<<": "<<bt.getBit(val, i)->bit<<endl;
}cout<<"The value is: "<<bt.getValue(samplebt)<<endl;
return 0;
}
$ g++ bit_array.cpp $ a.out Enter 4 bit integer value(0 - 8): 7 Bit of 7 at positon 0: 1 Bit of 7 at positon 1: 1 Bit of 7 at positon 2: 1 Bit of 7 at positon 3: 0 The value is: 7 ------------------ (program exited with code: 1) Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
👉 For weekly programming practice and certification updates, join
Sanfoundry’s official WhatsApp & Telegram channels
Related Posts:
- Check Programming Books
- Practice Programming MCQs
- Check Computer Science Books
- Check C++ Books
- Apply for Computer Science Internship