当memcpy遇到大小端问题

经常看到memcpy的源码都是针对char型做处理,当遇到short int 和char同时作为参数时,就得不到想要的结果,都是大小端惹的祸。


#include 
#include 
#include 

void *first_memcpy(void *dest,void *src, unsigned int count)
{
	assert((dest!=NULL)&&(src!=NULL));
	int i=0,k=0;
	if(dest==src)
		return src;
	char* d=(char*)dest;
	char* s=(char*)src;
	
	while(count--> 0)
	{
		*d++=*s++;
	}
	return dest;
}


void *second_memcpy(void *dest,void *src, unsigned int count)
{
	assert((dest!=NULL)&&(src!=NULL));
	int i=0,k=0;
	if(dest==src)
		return src;
	unsigned short* d=(unsigned short*)dest;
	char* s=(char*)src;
	
	while(count--> 0)
	{
		
		d[i]=(s[k]<<8)|s[k+1];
		i+=1;
		k+=2;
	}
	return dest;
}


void main()
{
        int i;
        unsigned short des[24]={0};
        unsigned char src[13]={0x12, 0x34, 0x56, 0x78};
        memcpy(des,src,4);
        
        printf("1 memcpy:\n");
        for(i=0;i<4;i++)
        {
                printf("%04x,",des[i]);
        }
         printf("\n");
         
         first_memcpy(des,src,4);
        
        printf("1 first_memcpy:\n");
        for(i=0;i<4;i++)
        {
                printf("%04x,",des[i]);
        }
         printf("\n");
         
        second_memcpy(des,src,4);
        printf("1 second_memcpy:\n");
        for(i=0;i<4;i++)
        {
                printf("%04x,",des[i]);
        }
         printf("\n");
}
执行结果:

1 memcpy:
3412,7856,0000,0000,
1 first_memcpy:
3412,7856,0000,0000,
1 second_memcpy:
1234,5678,0000,0000,

最后一种情况才是我们想要的!



你可能感兴趣的:(c,linux)