Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Add Comment
Please, Sign In to add comment