This is a follow-up of Comparing random number of bits.
I have a function that compares bits from a binary representation string and a chunk of memory and returns true if they are equal.
This is the function (which works as expected): I'll explain with comments what some external methods are supposed to do, accept that they work as expected for the sake of this question.
bool Bits::compareBinary(const char *string, size_t check_n_bits, size_t skip_n_bits){
bool match = true;
size_t bytes = (check_n_bits + 7) / 8;
size_t bytes_with_skip = (check_n_bits + skip_n_bits + 7) / 8;
if(this->canMoveForward(bytes_with_skip) == false) return false;
Bits *data = this->readBits(check_n_bits, skip_n_bits);
unsigned char *bin_string = Utils::removeSpaces(string);
size_t len = strlen((const char *) bin_string);
if(Utils::isValidBinString(bin_string) || len < check_n_bits) return false;
char tmp_bin_repr[9];
for(size_t i = 0; i < bytes; i++) {
int chars_to_compare = i + 1 == bytes ? check_n_bits % 8 : 8;
chars_to_compare = chars_to_compare == 0 ? 8 : chars_to_compare;
uint8_t c = data->read_uint8();
sprintf(tmp_bin_repr, BYTETOBINARYPATTERN, BYTETOBINARY(c));
if(memcmp(tmp_bin_repr, &bin_string[i * 8], chars_to_compare) != 0) {
match = false;
break;
}
}
}
Helper macro:
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
Let's call this function:
compareBinary(const char *string, size_t check_n_bits, size_t skip_b_bits)
As there are a couple of methods and a class I can't post here (for the sake of this question), you're free to explore the entire code here.
How is this function used? The function is a method of an object that contains some data. When this method is called, it compares as many bits from a binary string representation of data
as we pass it with the data contained in the object.
Example:
mObj->compareBinary("01010101 11110100 00", 18, 0);
This will compare 18 bits in total with the data that is hold in the object. First 8 chars of the passed string will be taken and the first byte of the data hold by the object will be converted to a string (using the helper macro). Then both will be compared. Second 8 chars, the same. Then we'd get the last 00
chars, take the third byte, convert it to a 8 chars binary representation, but only the first two chars will be compared.
This lets me compare a random number of bits with a simple binary representation of the data.
While the function works as expected and it's passing multiple unit tests, I believe it can be refactored and optimized. Can you give me any tips how to do it?