I recently created a library in C, which creates and stores binary arrays. My library uses the standard fixed data types and allocates no more than 8 bytes for a binary array (8 bytes = 64-bit unsigned long long
number). It also sets the binary equivalent at the bit level using the setBitsAt()
method to make it quite efficient.
I want to know if there is a more efficient way of creating and storing binary arrays in C.
Code snippet to create/store a binary array:
uint8_t* getBinaryArray(uint64_t num)
{
int8_t encodeBitIndex = 0,byteIndex = -1;
int8_t encodeBits = getEncodingBits(num);
binaryArrayLen = getBytes4mBits(encodeBits);
binaryArrayLen = (binaryArrayLen <= 0 || binaryArrayLen > BYTE) ? 0x1 : binaryArrayLen; /*Sanity check for size > 64bits*/
int8_t bitIndex = 0,binValue;
uint8_t *binaryArray = (uint8_t*)malloc(binaryArrayLen); /*Dynamic Array to store binary equivalent*/
memset(binaryArray,0x0,binaryArrayLen); /*Set 0 as initial value to Array*/
/*Storing binary equivalent in 1-bit each of binaryArray*/
for (encodeBitIndex = 0; encodeBitIndex < encodeBits; encodeBitIndex++,bitIndex++)
{
if(isNextByte(encodeBitIndex))
{
byteIndex += 1;
bitIndex = 0; /*-_- reset bitIndex for every byte*/
}
binValue = ((num >> encodeBitIndex) & 1) ? 1 : 0;
setBitsAt((binaryArray + byteIndex),binValue,bitIndex,encodeBits);
}
return binaryArray;
}
void setBitsAt(uint8_t *dest,uint64_t bits,uint8_t at,uint8_t nBits)
{
uint64_t mask = ((~0ULL) >> (sizeof(uint64_t) * BYTE - nBits)) << at;
*dest = (*dest & ~mask)|((bits<<at) & mask);
}
const int8_t getEncodingBits(uint64_t num)
{
return getRoundedBits((int8_t)fabs(floor(negLog2(num) - 1) + 1));
}
long double negLog2(uint64_t num)
{
long double negLogVal = 0.0f;
negLogVal = (num < 0) ? (sizeof(num) * BYTE) : (log2l(1.0L) - log2l(num));
return isNumInMaxRange(num) ? fabs(negLogVal) + 1 : negLogVal;
}
bool isNumInMaxRange(uint64_t num)
{
return ((num == (UINT8_MAX + 1U) || num == (UINT16_MAX + 1U) || num == (UINT32_MAX + 1ULL))) ? true : false;
}
const int8_t getRoundedBits(int8_t bits)
{
int8_t roundedBits;
for(roundedBits = BYTE; roundedBits <= QWORD; roundedBits+=BYTE)
{
if(bits >= 0 && bits <= roundedBits)
return roundedBits;
}
return -1;
}
setBitsAt()
is supposed to do? I don't think it does what you think it does, but I can't be sure because I don't know what it is supposed to do. \$\endgroup\$