Given (in C++)
char * byte_sequence;
size_t byte_sequence_length;
char * buffer;
size_t N;
Assuming byte_sequence
and byte_sequence_length
are initialized to some arbitrary length sequence of bytes (and its length), and buffer
is initialized to point to N * byte_sequence_length
bytes, what would be the easiest way to replicate the byte_sequence
into buffer
N
times? Is there anything in STL/BOOST that already does something like this?
For example, if the sequence were "abcd", and N
was 3, then buffer
would end up containing "abcdabcdabcd".
I would probably just go with this:
for (int i=0; i < N; ++i)
memcpy(buffer + i * byte_sequence_length, byte_sequence, byte_sequence_length);
This assumes you are dealing with binary data and are keeping track of the length, not using '\0'
termination.
If you want these to be c-strings you'll have to allocate an extra byte and add in the '\0'
a the end. Given a c-string and an integer, you'd want to do it like this:
char *RepeatN(char *source, size_t n)
{
assert(n >= 0 && source != NULL);
size_t length = strlen(source) - 1;
char *buffer = new char[length*n + 1];
for (int i=0; i < n; ++i)
memcpy(buffer + i * length, source, length);
buffer[n * length] = '\0';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With