Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to repeat a sequence of bytes into a larger buffer in C++

Tags:

c++

stl

boost

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".

like image 824
SCFrench Avatar asked Mar 12 '09 21:03

SCFrench


1 Answers

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';
}
like image 138
Eclipse Avatar answered Oct 13 '22 23:10

Eclipse