bod*_*ydo 15 c memory design-patterns memset
我今天面临一个问题,我需要将内存更改为某种模式,如0x 11223344,以便整个内存看起来像(十六进制):
1122334411223344112233441122334411223344112233441122334411223344...
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何使用memset(),因为它只需要一个字节,而不是4个字节.
有任何想法吗?
谢谢,Boda Cydo.
在OS X上,一个memset_pattern4( )用于此; 我希望其他平台有类似的API.
我不知道一个简单的可移植解决方案,除了用循环填充缓冲区(这非常简单).
递归复制内存,使用您已经填充的区域作为每次迭代的模板(O(log(N)):
int fillLen = ...;
int blockSize = 4; // Size of your pattern
memmove(dest, srcPattern, blockSize);
char * start = dest;
char * current = dest + blockSize;
char * end = start + fillLen;
while(current + blockSize < end) {
memmove(current, start, blockSize);
current += blockSize;
blockSize *= 2;
}
// fill the rest
memmove(current, start, (int)end-current);
Run Code Online (Sandbox Code Playgroud)
[编辑]我对"O(log(N))"的意思是运行时将比手动填充内存快得多,因为memmove()通常使用特殊的,手动优化的快速组装循环.
一种有效的方法是将指针转换为所需大小的指针(以字节为单位)(例如,uint32_t为4个字节)并填充整数.虽然这有点难看.
char buf[256] = { 0, };
uint32_t * p = (uint32_t *) buf, i;
for (i = 0; i < sizeof(buf) / sizeof(* p); i++) {
p[i] = 0x11223344;
}
Run Code Online (Sandbox Code Playgroud)
没测试过!
| 归档时间: |
|
| 查看次数: |
11904 次 |
| 最近记录: |