/*********************************************************
*CopyRight @piaoxiang.zhang
*******************************************************/
#include <stdio.h>
#define SWH_16(arg) swap_half_16_##arg
#define funVar(xxx) printf( "%s initial data is:\n", #xxx )
typedef union {
uint8_t AL[2];
uint16_t AX;
}UC_16_t;
void swap_half_16_1st(uint16_t *in,int len)
{
printf("\n%s start:\n",__func__) ;
UC_16_t *tmp=(UC_16_t *)in;
uint8_t t;
int i;
for(i=0;i<len;i++)
{
t=tmp->AL[0];
tmp->AL[0]=tmp->AL[1];
tmp->AL[1]=t;
tmp++;
}
}
void swap_half_16_2nd(uint16_t *in,int len)
{
printf("\n%s start:\n",__func__) ;
uint8_t *tmp=(uint8_t *)in,t;
int i;
for(i=0;i<len*2;i+=2)
{
t=tmp[i];
tmp[i]=tmp[i+1];
tmp[i+1]=t;
}
}
void swap_half_16_3rd(uint16_t *in,int len)
{
printf("\n%s start:\n",__func__) ;
int i;
for(i=0;i<len;i++)
{
in[i]=in[i]>>8|in[i]<<8;
}
}
void swap_half_16_4th(uint16_t *data,int len)
{
printf("\n%s start:\n",__func__) ;
uint8_t *tmp=(uint8_t *) data;
while(len>0)
{
__asm( "movb 0(%%esi),%%ah\n\t"
"movb 1(%%esi),%%al\n\t"
"movw %%ax,(%%esi)\n\t"
:"+a"(data)
:"S"(tmp));
tmp+=2;
len--;
}
}
int main(int argv ,char **argc)
{
uint16_t data[4]={0x1312,0x1512,0x1712,0x1812};
funVar(data);
printf("0x%X,0x%X,0x%X,0x%X\n",data[0],data[1],data[2],data[3]);
SWH_16(1st)(data,4);
printf("0x%X,0x%X,0x%X,0x%X\n",data[0],data[1],data[2],data[3]);
SWH_16(2nd)(data,4);
printf("0x%X,0x%X,0x%X,0x%X\n",data[0],data[1],data[2],data[3]);
SWH_16(3rd)(data,4);
printf("0x%X,0x%X,0x%X,0x%X\n",data[0],data[1],data[2],data[3]);
SWH_16(4th)(data,4);
printf("0x%X,0x%X,0x%X,0x%X\n",data[0],data[1],data[2],data[3]);
system("pause");
return 0 ;
}
16bit数据高低8位交换的4种实现方法
最新推荐文章于 2024-06-25 13:39:00 发布