是否有接受大于 char 的整数的 memset()? [英] Is there memset() that accepts integers larger than char?

查看:20
本文介绍了是否有接受大于 char 的整数的 memset()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有设置大于 1 个字节(字符)的值的 memset() 版本?例如,假设我们有一个 memset32() 函数,因此我们可以使用它执行以下操作:

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 following:

int32_t array[10];
memset32(array, 0xDEADBEEF, sizeof(array));

这将在数组的所有元素中设置值 0xDEADBEEF.目前在我看来这只能通过循环来完成.

This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.

特别是,我对 64 位版本的 memset() 感兴趣.知道这样的吗?

Specifically, I am interested in a 64 bit version of memset(). Know anything like that?

推荐答案

void memset64( void * dest, uint64_t value, uintptr_t size )
{
  uintptr_t i;
  for( i = 0; i < (size & (~7)); i+=8 )
  {
    memcpy( ((char*)dest) + i, &value, 8 );
  }  
  for( ; i < size; i++ )
  {
    ((char*)dest)[i] = ((char*)&value)[i&7];
  }  
}

(解释,如评论中所要求:当您分配给一个指针时,编译器假定该指针与类型的自然对齐对齐;对于 uint64_t,即 8 个字节.memcpy() 不做这样的假设.在某些硬件未对齐访问是不可能的,因此分配不是一个合适的解决方案,除非您知道未对齐访问在硬件上工作的代价很小或没有惩罚,或者知道它们永远不会发生,或两者兼而有之.编译器将替换小 memcpy()s 和memset()s 具有更合适的代码,因此它看起来并不那么可怕;但是如果您确实知道足够多以保证分配始终有效并且您的分析器告诉您它更快,您可以用分配替换 memcpy.第二个如果要填充的内存量不是 64 位的倍数,则存在 for() 循环.如果您知道它总是如此,您可以简单地删除该循环.)

(Explanation, as requested in the comments: when you assign to a pointer, the compiler assumes that the pointer is aligned to the type's natural alignment; for uint64_t, that is 8 bytes. memcpy() makes no such assumption. On some hardware unaligned accesses are impossible, so assignment is not a suitable solution unless you know unaligned accesses work on the hardware with small or no penalty, or know that they will never occur, or both. The compiler will replace small memcpy()s and memset()s with more suitable code so it is not as horrible is it looks; but if you do know enough to guarantee assignment will always work and your profiler tells you it is faster, you can replace the memcpy with an assignment. The second for() loop is present in case the amount of memory to be filled is not a multiple of 64 bits. If you know it always will be, you can simply drop that loop.)

这篇关于是否有接受大于 char 的整数的 memset()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆