Search code examples
cmemorydesign-patternsmemset

How to memset() memory to a certain pattern instead of a single byte?


I need to write a repeating pattern to memory (e.g. 0x11223344), so that the whole memory looks like (in hex):

1122334411223344112233441122334411223344112233441122334411223344...

I can't figure out how to do it with memset() because it takes only a single byte, not 4 bytes.

Any ideas?


Solution

  • An efficient way would be to cast the pointer to a pointer of the needed size in bytes (e.g. uint32_t for 4 bytes) and fill with integers. It's a little ugly though.

    char buf[256] = { 0, };
    uint32_t * p = (uint32_t *) buf, i;
    
    for (i = 0; i < sizeof(buf) / sizeof(* p); i++) {
        p[i] = 0x11223344;
    }
    

    Not tested!