1. memcpy. An often being asked interview question. The key is to handle address overlap.
void *memcpy(void *dest, const void *src, size_t n)
{
int i, l;
void *dst;
char *d, *s;
d = dest;
s = src;
dst = dest;
if (!dest || !src)
return NULL;
if (s < d && (s+n > d)) { // only (s < d) is necessary
s += n - 1;
d += n - 1;
for (i = 0; i < n; i++) {
*d-- = *s--;
}
return dst;
}
for (i = 0; i < n; i++) {
*d++ = *s++;
}
return dst;
}
2. strcpy. another thought about strcpy(), does address overlap need to consider?
char *strcpy(char *dst, const char *src)
{
if (!dst || !src)
return NULL;
char *d = dst;
int len = strlen(src);
if (src < dst && (src + len+1 > dst)) {
int i;
src += len;
dst += len;
for (i = 0; i < len+1; i++) {
*dst-- = *src--;
}
return d;
}
while ((*dst++ = *src++) != '\0');
return d;
}
3. count how many bit is 1 in one byte.
// 常规方法
char count1(int n)
{
int i;
int c = 0;
for (i = 0; i < 32; i++) {
c += (n & (1 << i)) ? 1 : 0;
}
return c;
}
// 较优算法
char count1_bitand(int n)
{
int c = 0;
while(n) {
// n&(n-1)的作用是清除n的二进制数中最后一个1,
// 即如果a=101011000B,那么清除最后一个1之后就变成了a=101010000B.
n &= n - 1;
c++;
}
return c;
}