How to use __byteswap() function ?

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

How to use __byteswap() function ?

跳至解决方案
4,866 次查看
Amit_Kumar1
Senior Contributor II

Hi

I am using K60 with cw 10.6. I am writing some values to serial port in binary format , the sequence of the values are same but they are flipped i.e

i am printing

AB BC CD 00                    // 32 bit value

i am getting

00 CD BC AB         

This issue was due to the little endian nature of uc so i wanted to swap the 32 bit data and then print it. I am unable to find any syntax for __byteswap32();

Kind Regards

Amit Kumar

标记 (3)
0 项奖励
回复
1 解答
3,847 次查看
Amit_Kumar1
Senior Contributor II

the syntax is __builtin_bswap32(); finally found out.

在原帖中查看解决方案

0 项奖励
回复
3 回复数
3,848 次查看
Amit_Kumar1
Senior Contributor II

the syntax is __builtin_bswap32(); finally found out.

0 项奖励
回复
3,846 次查看
Amit_Kumar1
Senior Contributor II

Hi

This byte swap didn't work for float values , Is there anything like this for float values also ??

Kind Regards

Amit Kumar

0 项奖励
回复
3,846 次查看
egoodii
Senior Contributor III

If your compiler is 'forcing' the type 'uint32' for the input/output of that intrinsic function, then I simply suggest you declare the associated vars with a 'union' of float and uint32 (and int32?) and let the compiler 'look' at them the appropriate way in the appropriate places (var.fval, var.uval, var.sub.s32, var.sub.s16.lo, var.sub.s8.hh etc.).

typedefunion{       //Any of three ways to look at a 32-bit number
floatfval;
uint32_tuval;
union{           //Byte/Word/Dword, little-endian

   struct{

  uint16_t lo;
  int16_t hi;

   } s16;

   struct{

uint8_t ll;
uint8_t lm;
uitn8_t hm;
int8_t hh;

   } s8;

   int32_t s32;

}sub;

}Multi_t;

For example:

Multi_t inval, outval;

inval.fval = 3.1415927f;

outval.uval = __builtin_bswap32(inval.uval);  //For the IAR compiler, use __REV( );

The net result in outval.uval being 0xDB 0F 49 40

You can also use this union to 'assemble' (or disassemble!) something, say from a 'byte peripheral' (big endian order in this case!)

outval.sub.s8.hh = GetSPI( );     //Or some such byte-fetch

outval.sub.s8.hm = GetSPI( );

outval.sub.s8.lm = GetSPI( );

outval.sub.s8.ll = GetSPI( );

Now outval.fval is your whole floating-point number (for instance), assembled using the direct 'byte' instructions of the CPU without << and &0xFF ops (and reliance on the compiler to make THAT efficient).  Furthermore, if you move this code to a 'big endian' CPU environment all you have to do is swap the order of the s8 and s16 'sub elements' in the union and the rest of your code will STILL have the correct results!

0 项奖励
回复