简体   繁体   中英

what's the most efficient way in c++ to break a bool array into an int array

I have a function where the input and output are bool arrays (longer than the simple example). Internally the function works on fixed length integers (ie integers that are exactly 12 bits or 7 bits, ...). So the first step is to convert the input bool array into an equivalent int array. Here's an example :

 bool bits[10*12];
 unsigned int ints[10];

 for(int k=0;k<10;k++)
  {
   x=1;
   t=0;
   for(int b=0;b<12;b++)
   {
    t+=x*bits[k*12+b];
    x*=2;
   }
   ints[k]=t;
 }

which converts an input array of 120 bits to an int array with 10 entries, each being 12 bits. This works fine but I'd like to see if there are more efficient ways of doing this.

You have to look at every single bit at least once. There is no way around it. So the most efficient way is O(n) where n is the number of bits.

Your algorithm is O(n) . Congratulations.

The only way to be more efficient is to not need a conversion at all. Why don't all your code work with 12bit ints?

Or did you maybe want more performant code instead of more efficient?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM