#define OP_T_THRES 16
#define op_t unsigned long int
#define OPSIZ (sizeof(op_t))
void* memcpy(void* dstpp,const void* srcpp, size_t len)
{
unsigned long int dstp = (long int) dstpp;
unsigned long int srcp = (long int) srcpp;
/* Copy from the beginning to the end. */
/* If there not too few bytes to copy, use word copy. */
if (len >= OP_T_THRES)
{
/* Copy just a few bytes to make DSTP aligned. */
len -= (-dstp) % OPSIZ;
BYTE_COPY_FWD (dstp, srcp, (-dstp) % OPSIZ);
/* Copy from SRCP to DSTP taking advantage of the known
alignment of DSTP. Number of bytes remaining is put
in the third argumnet, i.e. in LEN. This number may
vary from machine to machine. */
WORD_COPY_FWD (dstp, srcp, len, len);
/* Fall out and copy the tail. */
}
/* There are just a few bytes to copy. Use byte memory operations. */
BYTE_COPY_FWD (dstp, srcp, len);
return dstpp;
}
(-dstp) % OPSIZ
32位机上,OPSIZ为4
dstp为无符号整型,而-dstp会取得负数补码,但是dstp为无符号。
例如:
unsigned long int val = -3;
cout << val << endl; //输出4294967293
val的16进制值为0xfffffffd(刚好为-3的补码),但输出4294967293,将(fffffffd)按照无符号数输出。
原理:(参考:http://blog.163.com/xucan168@126/blog/static/651449902008367257385/)
范围为[0,M)的整数计量系统,其模为M。若a+b = M, 则a与b互为补数。
可以考虑8位二进制数,M为2^8=256。若a = 17,则 b = 239。

假如dstp地址为17,现在要算出其离最近一个对齐地址之间的距离。32位机以4字节对齐,而复制到dstp所指向的区域,
所以只能向后找,最靠近的地址为20。
而如果dstp % 4,所得的即为与16的距离。可以想象,17/4的4,余数1即为16-17的距离。同样,数239,如果以末端256开始算起。
即239/4为239中包含多少个4,余数即为17-20的距离,即我们所求。
根据这个原理,我们只需求原数的补数,求补数的余数,即为所求距离。
BYTE_COPY_FWD
#define BYTE_COPY_FWD(dst_bp, src_bp, nbytes)
do
{
size_t __nbytes = (nbytes);
while (__nbytes > 0)
{
byte __x = ((byte *) src_bp)[0];
src_bp += 1;
__nbytes -= 1;
((byte *) dst_bp)[0] = __x;
dst_bp += 1;
}
} while (0)进行字节拷贝,使得dstp移动到对齐地址处。
本文深入探讨了内存对齐的概念及其在memcpy函数中的应用。通过对特定宏定义和操作的理解,解释了如何利用内存对齐来提高数据复制效率。特别关注了在不同机器架构下,如何调整对齐方式以实现最佳性能。
773

被折叠的 条评论
为什么被折叠?



