This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

16 Bit swap by 8bits

Hello

For my SPI communication, I need send a 16 bit data.

Then I write 16 bit variable to spiaRegs.TXBUF:

MyUINT16Var= 0x1234;

spiaRegs.TXBUF = MyUINT16Var;

by this way, SPI send data with following bit flow:  Fisrt transmitted bit: 0, second: 0, ... 0 1     0 0 1 0     0 0 1 1    0 1 0 0 .

Then the transmitted data are MSB first : 0x1234.

For My end device, I need following flow : 0 0 1 1   0 1 0 0   0 0 0 1     0 0 1 0  => 0x3412.

To resume, I need before transmit swap MSB and LSB of my 16 bits variable.

I seen compiler instruction : __flip16(MyVar) (in www.ti.com/lit/ug/spru514j/spru514j.pdf)

, but the result is 0x2C48 because is the bit was reverse. I need to reverse the Byte. : 0x12 34 become 0x34 12.

I seen in http://www.ti.com/lit/ug/spruhs1a/spruhs1a.pdf the assembler instruction

VBITFLIP VRa — Bit Flip which seem correspond to compiler __flip16(MyVar)

I also seen :

VCFLIP VRa Swap Upper and Lower Half of VCU Register

This instruction seem ok for me. 

But I not found the correspondance in C compiler. The I try asm("VCFLIP VR0;");

Are they compiler instruction like _flip16 which allow to swap 8 LSB bit with 8MSB bit of a variable?

 

  • A,

    You cannot do inline assembly such as asm("VCFLIP VR0"); because you cannot guarantee that the data of interest will be in the VR0 register.

    The easiest approach to do what you need is just code up some shifting and masking in C to swap the bytes. This will not be overly efficient, but then how often do you need to do this anyway? It probably doesn't matter.

    If you need more performance, or just wanted to get fancy, you can try the __byte intrinsic. This uses the MOVB instruction. Just off the top of my head, you would store off the bytes to temporary vars, and then reload then in the desired order. A sequence of 4 stores followed by 4 loads would do the job. If you wanted to get real fancy, you could code it in hand assembly (you would have to create a C-callable function, call it swap() for example).

    Regards,
    David
  • Yes, In fact it is the ACC register which is used in my case (AL), so instruction not work with AL...
    The I do (MyVarr >>8) + (MyVar <<8)...
    THis function is for SPI send, on a device where the timing is very, very important.
    The number of Read/write on the SPI device should be important, then it is important this optimize this part of code.
    I will try to implement a specific swap macro in assembler and will compare if it is beter than (>>8 + <<8)...