daily pastebin goal
56%
SHARE
TWEET

Untitled

a guest Nov 24th, 2017 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. uint8_t* getBinaryArray(uint64_t num)
  2. {
  3.     int8_t encodeBitIndex = 0,byteIndex = -1;
  4.     int8_t encodeBits = getEncodingBits(num);
  5.  
  6.     binaryArrayLen = getBytes4mBits(encodeBits);
  7.     binaryArrayLen = (binaryArrayLen <= 0 || binaryArrayLen > BYTE) ? 0x1 : binaryArrayLen; /*Sanity check for size > 64bits*/
  8.  
  9.     int8_t bitIndex = 0,binValue;
  10.     uint8_t *binaryArray = (uint8_t*)malloc(binaryArrayLen); /*Dynamic Array to store binary equivalent*/
  11.  
  12.     memset(binaryArray,0x0,binaryArrayLen); /*Set 0 as initial value to Array*/
  13.  
  14.     /*Storing binary equivalent in 1-bit each of binaryArray*/
  15.     for (encodeBitIndex = 0; encodeBitIndex < encodeBits; encodeBitIndex++,bitIndex++)
  16.     {
  17.  
  18.         if(isNextByte(encodeBitIndex))
  19.         {
  20.             byteIndex += 1;
  21.             bitIndex = 0; /*-_- reset bitIndex for every byte*/
  22.         }
  23.  
  24.         binValue = ((num >> encodeBitIndex) & 1) ?  1 : 0;
  25.         setBitsAt((binaryArray + byteIndex),binValue,bitIndex,encodeBits);
  26.     }
  27.     return binaryArray;
  28. }
  29.  
  30. void setBitsAt(uint8_t *dest,uint64_t bits,uint8_t at,uint8_t nBits)
  31. {
  32.     uint64_t mask = ((~0ULL) >> (sizeof(uint64_t) * BYTE - nBits)) << at;
  33.     *dest = (*dest & ~mask)|((bits<<at) & mask);
  34. }
  35.  
  36. const int8_t getEncodingBits(uint64_t num)
  37. {
  38.     return getRoundedBits((int8_t)fabs(floor(negLog2(num) - 1) + 1));
  39. }
  40.  
  41. long double negLog2(uint64_t num)
  42. {
  43.     long double negLogVal = 0.0f;
  44.     negLogVal = (num < 0) ? (sizeof(num) * BYTE) : (log2l(1.0L) - log2l(num));
  45.     return isNumInMaxRange(num) ?  fabs(negLogVal) + 1 : negLogVal;
  46. }
  47.  
  48. bool isNumInMaxRange(uint64_t num)
  49. {
  50.     return ((num == (UINT8_MAX  + 1U) || num == (UINT16_MAX  + 1U) || num == (UINT32_MAX  + 1ULL))) ?  true : false;
  51. }
  52.  
  53. const int8_t getRoundedBits(int8_t bits)
  54. {
  55.     int8_t roundedBits;
  56.     for(roundedBits = BYTE; roundedBits <= QWORD; roundedBits+=BYTE)
  57.     {
  58.         if(bits >= 0 && bits <= roundedBits)
  59.             return roundedBits;
  60.     }
  61.     return -1;
  62. }
RAW Paste Data
Top