我试图实现一个版本的memset来一次写一个字而不是逐个字节。 我目前使用的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* set in memory one word at a time
dest: destination
ch: the character to write
count: how many copies of ch to make in dest */
void wmemset(char *dest, int ch, size_t count) {
long long int word; // 64-bit word
unsigned char c = (unsigned char) ch; // explicit conversion
int i, loop, remain;
for (i = 0, word = 0; i < 8 ; ++i) {
word |= ((long long int)c << i * 8);
}
loop = count / 8;
remain = count % 8;
for (i = 0; i < loop; ++i, dest += 8) {
*dest = word; // not possible to set 64-bit to char
}
for (i = 0; i < remain; ++i, ++dest) {
*dest = c;
}
}
int main() {
char *c;
c = (char *) malloc(100);
wmemset(c, 'b', 100);
for (int i = 0; i < 100; i++)
printf("%c", c[i]);
}
我认为64位字会溢出到指针的其余字节,但它看起来并非如此。 如何一次设置一个单词?
编辑:添加了一些评论并添加了主要功能。