一些地方常用到要颠倒数据的情况,下面分别正对8,16,32的数据进行处理。 //把字节颠倒过来,如0x32变成0x4C // 0x32: 0011 0010 // 0x4C: 0100 1100
uint8_t InvertUint8(uint8_t in)
{
uint32_t i;
uint8_t tmp = 0;
for(i=0; i< 8; i++)
{
if(in & (1 << i))
tmp |= 1 << (7 - i);
}
return tmp;
}
uint16_t InvertUint16(uint16_t in)
{
uint32_t i;
uint16_t tmp = 0;
for(i=0; i< 16; i++)
{
if(in & (1 << i))
tmp |= 1 << (15 - i);
}
return tmp;
}
uint32_t InvertUint32(uint32_t in)
{
uint32_t i;
uint32_t tmp = 0;
for(i=0; i< 32; i++)
{
if(in & (1 << i))
tmp |= 1 << (31 - i);
}
return tmp;
}
如果是一系列的数据要交换,为了提高速度,要进行优化,比如对一系列的8bit数据进行颠倒处理:
void InvertUint8_len(uint8_t *pdst,uint8_t *psrc,uint32_t len)
{
uint32_t i,j;
uint8_t tmp,in;
for(j = 0; j < len; i++)
{
in = *psrc++;
tmp = 0;
for(i=0; i< 8; i++)
{
if(in & (1 << i))
tmp |= 1 << (7 - i);
}
*pdst++ = tmp;
}
}
|