comparing an array of bits

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • byenary
    New Member
    • Sep 2007
    • 3

    #1

    comparing an array of bits

    Hello
    I have got 2 variabeles in an application the type;
    typedef guint32 data[8]; -> so 256 bits
    Now i have a load of data of this type derrived from fileheaders.
    I want to compare these and get a number of how many bits are set to 1 on the same place.
    So for Ex with 8 bits
    data1 : 00110011
    data2 : 00100010
    This should give me 2 as an answer. I don't really know how to do this i am not that expririenced. I guess ORRING the whole array with the other or something like bitshifting is what i should do but i don't know how.

    Thank you very much for any help!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by byenary
    This should give me 2 as an answer. I don't really know how to do this i am not that expririenced. I guess ORRING the whole array with the other or something like bitshifting is what i should do but i don't know how.
    XORing (^) the 2 values will give a result that has bits set where the bits in the 2 original values do not have the same value.

    Having got this result count the number of bits set in it by, testing bit 0 shifting right 1 place and continuing while the result != 0.

    Comment

    • byenary
      New Member
      • Sep 2007
      • 3

      #3
      made a little test ap wich does the job
      [code=c]
      #include <stdio.h>

      void show_binary(uns igned short u);
      void show_lastbit(un signed short u);
      unsigned short count_ones(unsi gned short test);

      int main(void)
      {
      unsigned short getal1;
      unsigned short getal2;
      getal1 = 14531;
      getal2 = 14045;
      show_binary(get al1);
      show_binary(get al2);
      unsigned short test = getal1 & getal2;
      show_binary(tes t);
      printf("aantal = %d",count_ones( test));
      /*
      0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 1
      0 0 1 1 0 1 1 0 1 1 0 1 1 1 0 1
      0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 1
      1 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 aantal = 5
      */
      return 0;
      }

      unsigned short count_ones(unsi gned short test){
      int aantal = 0;
      int i=0;
      for(i=0;i<sizeo f(test)*8;i++){
      if(test & 1){
      printf("1 ");
      aantal++;
      }
      else
      printf("0 ");
      test = test >> 1;
      }
      return aantal;
      }

      void show_binary(uns igned short u)
      {
      int n;

      for( n = 32768; n > 0; n = n / 2 )
      if(u & n)
      printf("1 ");
      else
      printf("0 ");

      printf("\n");
      }

      void show_lastbit(un signed short u)
      {
      int n;
      if(u & 1)
      printf("1 ");
      else
      printf("0 ");

      printf("\n");
      }[/code]
      Last edited by sicarie; Sep 24 '07, 01:02 PM. Reason: Code tags

      Comment

      Working...