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

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

问题描述

有memset的(),它设置一个值,大于1个字节(char)放大的版本?例如,假设我们有一个memset32()函数,因此使用它,我们可以做到以下几点:

  int32_t阵列[10];
memset32(数组,0xDEADBEEF,sizeof的(阵列));

这将设置值0xDEADBEEF阵列中的所有元素。目前,在我看来这只能是一个循环完成。

具体来说,我感兴趣的是memset的64位版本()。知道这样的事情?


解决方案

 无效memset64(无效* DEST,uint64_t中值,类型uintptr_t大小)
{
  uintptr_t的我;
  对于(I = 0; I&≤(大小及(〜7)); I + = 8)
  {
    的memcpy(((CHAR *)DEST)+ I,安培;价值8);
  }
  对于(; I<大小;我++)
  {
    ((字符*)DEST)[I] =((字符*)及值)[我及7]。
  }
}

(解释的要求,在注释:当你分配给一个指针,编译器假定指针对准该类型的自然对齐;对于uint64_t中,即8个字节的memcpy()没有这样的假设上。一些硬件对齐访问是不可能的,所以赋值不是一个合适的解决方案,除非你知道不对齐与小或没有处罚的硬件访问工作,或者知道他们会不会发生,或两者兼而有之。编译器将取代小的memcpy()S和memset的()s的更适合code所以它并不像可怕的是它看起来,但如果你知道不足以保证分配将总是工作和你的分析器告诉你那是快,你可以​​通过赋值取代的memcpy ,第二个为()循环是present的情况下,内存被填充的数量不是64位的倍数。如果你知道它永远是,你可以简单地丢弃循环。)

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));

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.

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];
  }  
}

(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天全站免登陆