Search code examples
arrayscfillmemcpymemset

What is the fastest way to initialize an array in C with only two bytes for all elements?


Assume that we have an array called:

uint8_t data_8_bit[2] = {color >> 8, color & 0xff};

The data is 16-bit color data. Our goal is to create an array called:

uint8_t data_16_bit[2*n];

Where n is actually the length of 16-bit data array. But the array data_16_bit cannot hold 16-bit values so therefore I have added a 2*n as array size.

Sure, I know that I can fill up the array data_16_bit by using a for-loop:

for(int i = 0; i < n; i++)
    for(int j = 0; j < 2; j++)
        data_16_bit[j*i] = data_8_bit[j];

But there must be a faster way than this? memset or memcpy?


Solution

  • IMO the easiest one to optimize by the compiler (and very safe as well) is

    void foo(uint16_t color, uint8_t *arr16, size_t n)
    {
        uint8_t data_8_bit[2] = {color >> 8, color & 0xff};
    
        while(n--)
        {
            memcpy(arr16 + n * 2, data_8_bit, 2);
        }
    }
    

    https://godbolt.org/z/8Wh5Pc3aP