Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding a vector with 0's if it's not a multiple of 8

How can I pad out a vector with 0's if it is not a multiple of 8 bytes? In the following code I work out the offset and add to the vector to make sure it always has 8 values. I would like to pad this out with 0's and I am wondering what is the most efficient way to do this.

For example:

Input: 4444

With padding: 4444000000000000

The code I have so far is:

if ((vector1.size() % 8) != 0)
{
  for (std::vector<unsigned char>::iterator itr = vector1.begin(); itr != vector1.end(); itr ++)
  {
    vector1.push_back(fmod(vector1.size(), 8));

    if(vector1.size() == 8)
      break;
  }
}
like image 778
Zeus7 Avatar asked Sep 25 '17 13:09

Zeus7


People also ask

How do you set a vector to all zeros?

A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.

How many numbers can a vector have?

max_size() is the theoretical maximum number of items that could be put in your vector. On a 32-bit system, you could in theory allocate 4Gb == 2^32 which is 2^32 char values, 2^30 int values or 2^29 double values.

How do you add all the numbers in a vector?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.


1 Answers

UPDATE: One-liner (original more readable version below):

vec.resize(vec.size() + (8 - vec.size() % 8) % 8, 0);

Here's the code that should be quite efficient. It avoids multiple re-allocations and does nothing if no padding is needed.

const size_t nonPaddedSize = vec.size();
const size_t numPaddingElements = (8 - nonPaddedSize % 8) % 8;
if(numPaddingElements > 0)
    vec.resize(nonPaddedSize + numPaddingElements, 0);

Here's a live-example


Note: Originally the post suggested reserve + insert, but resize will do the same in a less verbose way.

like image 193
AMA Avatar answered Sep 17 '22 06:09

AMA