实现位数组的C ++程序
这是一个实现位数组的C++程序。位数组是一种紧凑地存储数据的数组数据结构。它基本上用于实现简单的数据结构。
算法
函数和伪代码:
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.
范例程式码
#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; }
输出结果
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