I created functions to read bit data from arbitrary bit position of a char
array to long long int
, and I also created a function to write data to a char
array from vector bool
.
However, I do not really like my implementation since I think it has a burdensome implementation when reading and writing bits. Can anyone see my implementation and enlighten me on a better implementation?
Here is my implementation to write bit data from vector<bool> bitdataForModification
.
unsigned char*& str
is the originalchar
array.int startBitLocation
is an arbitrary bit position to read from.int sizeToModify
is the size in bits for modification.
void setBitDataToBitPosition(unsigned char*& str, int startBitLocation, int sizeToModify, std::vector<bool>& bitdataForModification){
int endBitLocation = startBitLocation + sizeToModify-1;
int sizeChar = (endBitLocation - startBitLocation)/8;
//Save leftover data
int startCharPosition = startBitLocation/8;
int startLeftOverBits = startBitLocation%8;
//endPosition
int endCharPosition = endBitLocation/8;
int endLeftOverBits = 7-(endBitLocation%8);
unsigned char tempChar = str[startCharPosition];
unsigned char tempLastChar = str[endCharPosition]; // store last char
int posBitdata = 0;
for(int i = 0 ; i < startLeftOverBits; i++){
str[startCharPosition] <<= 1;
str[startCharPosition] = (str[startCharPosition] | ((tempChar >> (7-i)) & 0x1));
}
for(int i = startCharPosition*8 + startLeftOverBits ; i <= endBitLocation ; i++){
str[i/8] <<= 1;
if(posBitdata <= endBitLocation){
str[i/8] = (str[i/8] | ((bitdataForModification[posBitdata]) & 0x1));
posBitdata++;
}
}
for(int i = 0 ; i < endLeftOverBits ; i++){
str[endCharPosition] <<= 1;
str[endCharPosition] = (str[endCharPosition] | ((tempChar >> i) & 0x1));
}
}
I do not like this function because it copies from the original char[]
to a temp char[]
and copies back the bits I need.
Following is my read function I implemented. It reads from a char
array and copies the data to long long int data
.
void getBitDataFromBitPosition(unsigned char* str, int startBitLocation, int sizeToRead, unsigned long long* data){
int endBitLocation = startBitLocation + sizeToRead;
int sizeChar = (endBitLocation - startBitLocation)/8;
int startCharPosition = startBitLocation/8;
int endCharPosition = endBitLocation/8 +1;
vector<bool> bitData;
int bitCnt = 0;
for(int i = startCharPosition; i < endCharPosition; i++){
unsigned char tempChar = str[i];
for(int j = 7 ; j >= 0 ; j--){
int curLoc = ((i*8)+(bitCnt%8));
if(curLoc >= startBitLocation){
if(curLoc < endBitLocation){
bool temp = ((str[i] >> j) & 0x1);
bitData.push_back(temp);
}
}
bitCnt++;
}
}
for(int i = bitData.size() -1 ; i >= 0 ; i--){
*data <<= 1;
*data = (*data | bitData[bitData.size()-i-1]);
}
}
I think it is a burden to copy to a bool vector
and copy back to long long int
. Can anyone provide a better solution for me?