Search code examples
carraysuint64uint16

Fill uint16_t array with uint64_t data in C


I'm having a problem trying to save a data of uint64_t size into 4 uint16_t positions in array without using any loop... Here is a part of my code:

static int send(uint16_t addr, const void *data)
{
    uint16_t frame[7];
    /* Here I want to save in frame[2], frame[3], frame[4] and frame[5] the data recieved by parameter */

}

Thanks in advance! :)


Solution

  • typedef union
    {
        uint64_t u64;
        uint32_t u32[2];
        uint16_t u16[4];
        uint8_t u8[8];
    }UINT_UNION_T;
    
    uint16_t *saveU64(uint16_t *table, size_t position, uint64_t value)
    {
        UINT_UNION_T u = {.u64 = value};
    
        table[position] = u.u16[0];
        table[position + 1] = u.u16[1];
        table[position + 2] = u.u16[2];
        table[position + 3] = u.u16[3];
        return table;
    }
    

    Or

      memcpy(table + position, &value, sizeof value);