Is there memset() that accepts integers larger than char?

前端 未结 8 620
时光说笑
时光说笑 2020-12-05 00:25

Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let\'s say we have a memset32() function, so using it we can do the followi

8条回答
  •  执念已碎
    2020-12-05 00:35

    If you're just targeting an x86 compiler you could try something like (VC++ example):

    inline void memset32(void *buf, uint32_t n, int32_t c)
    {
      __asm {
      mov ecx, n
      mov eax, c
      mov edi, buf
      rep stosd
      }
    }
    

    Otherwise just make a simple loop and trust the optimizer to know what it's doing, just something like:

    for(uint32_t i = 0;i < n;i++)
    {
      ((int_32 *)buf)[i] = c;
    }
    

    If you make it complicated chances are it will end up slower than simpler to optimize code, not to mention harder to maintain.

提交回复
热议问题