Finding binary ones in a number with Two's complement, C -


i think might making bit complicated. supposed pass in long, , return number of 1's in binary representation of number. negatives, return two's complement. have positives working, two's complement bit off. tips making work appreciated.

unsigned int binaryonescounter(long n) {    unsigned int onecounter, negcounter;   int binarystorage[63];   int index, negflag;    onecounter = negflag = index = 0;     int i;   (i = 0; < 63; ++i)   {     binarystorage[i] = 0;   }    if(n < 0) {     if (n == -1){       onecounter = 63 + 1;     } else {       /* negate , add 1*/       negflag = 1;       n = (n * -1) + 1;     }   }   while (n>=1) {     if (n%2 == 1) {       onecounter++;       binarystorage[index] = 1;     }     else if (n%2 == 0) {       binarystorage[index] = 0;     }     n = n/2;   }     if (negflag == 1 && n != 1) {     negcounter = 64;     onecounter = negcounter - onecounter;   }   return onecounter; } 

it overcomplicated

int countones(long long i) {     int nones = 0;     unsigned long long *ptr = &i;      while (*ptr)     {         nones += *ptr & 1;         *ptr >>= 1;     }     return nones; } 

ps -4 has 62 ones not 63 0b1111111111111111111111111111111111111111111111111111111111111100

here bit more universal 1 (counts in object)

int getbit(void *obj, size_t bit);  size_t countbitsuniversal(void *obj, size_t osize) {     size_t nones = 0, tmp = osize;     osize <<= 3;      if (osize && osize > tmp)     {                 {             nones += getbit(obj, --osize);          } while (osize);     }     return nones; }  int getbit(void *obj, size_t bit) {     uint8_t *p = obj;      return !!(p[bit >> 3] & (1 << (bit & 7))); }  __________ usage example   double x; printf("%zu\n", countbitsuniversal(&x, sizeof(x)));  long long arr[100]; printf("%zu\n", countbitsuniversal(arr, sizeof(arr))); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -