C++ Program to Implement Bit Array

C++Server Side ProgrammingProgramming

This is a C++ program to implement Bit Array. A Bit Array is an array data structures that compactly stores data. It is basically used to implement a simple data structure.

Algorithm

Functions and pseudocodes:

Begin
   Function getBit(int val,int pos)
   singleBit->b = 0
   if(pos == 0)
      singleBit->b = val & 1
   else
      singleBit->b = ( val & (1 << pos ) ) >> pos
      return singleBit
   Function setBit(BitArr *bt,B *bit,int pos)
      bt->bVal[pos] = bit
      return bt
   Function getVal(BitArr *bArray)
   initialize val = 0
   initialize bVal = 0
   bVal = bArray->bVal[0]->b
   val= val|bVal
   for i = 1 to B_A_LENGTH-1
      bVal = bArray->bVal[i]->b
      bVal =bVal << i
      val=val | bVal
      return val
   done
End.

Example Code

 Live Demo

#include <iostream>
#include <string>
using namespace std;
#define B_A_LENGTH 4
typedef struct {
   unsigned int b : 1;
} B;
class BitArr {
   private:
   B **bVal;
   public:
   BitArr() {
      bVal = new B* [B_A_LENGTH];
   }
   B *getBit(int val,int pos) {
      B *singleBit = new B;
      singleBit->b = 0;
      if(pos == 0) {
         singleBit->b = val & 1;
      } else {
         singleBit->b = ( val & (1 << pos ) ) >> pos;
      }
      return singleBit;
   }
   BitArr *setBit(BitArr *bt,B *bit,int pos) {
      bt->bVal[pos] = bit;
      return bt;
   }
   int getVal(BitArr *bArray) {
      int val = 0;
      unsigned int bVal = 0;
      bVal = bArray->bVal[0]->b;
      val |= bVal;
      for(int i = 1; i < B_A_LENGTH; i++) {
         bVal = bArray->bVal[i]->b;
         bVal <<= i;
         val |= bVal;
      }
      return val;
   }
};
int main() {
   int v;
   cout<<"Enter 4 bit integer value (0 - 8): ";
   cin>>v;
   BitArr bt, *samplebt;
   samplebt = new BitArr;
   for (int i = 0; i < B_A_LENGTH; i++) {
      samplebt = bt.setBit(samplebt, bt.getBit(v, i), i);
      cout<<"Bit of "<<v<<" at positon "<<i<<": "<<"\n"<<bt.getBit(v, i)->b<<endl;
   }
   cout<<"The value is: "<<bt.getVal(samplebt)<<endl;
   return 0;
}

Output

Enter 4 bit integer value (0 - 8): 6Bit of 6 at positon 0:
0
Bit of 6 at positon 1:
1
Bit of 6 at positon 2:
1
Bit of 6 at positon 3:
0
The value is: 6
raja
Published on 29-Mar-2019 06:55:52
Advertisements