glibc memcpy

来源:互联网 发布:淘宝卖游戏号靠谱吗 编辑:程序博客网 时间:2024/05/21 22:15
#define OP_T_THRES    16#defineop_tunsigned 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移动到对齐地址处。


原创粉丝点击