How to swap bytes or words within a macro

How to swap bytes or words within a macro
none 0.0 0

I am using a CMT-SVR-102 to read string data from an Omron CJ2M PLC, and then sending it out via the OUTPORT in a macro to a Free Protocol device. The issue is that the bytes in the string data appears to be swapped. So instead of “ABCD” I get “BADC”.

Is there a way to swap the bytes from within the macro?

Hi @jnorris,

There are functions within our API to swap the high or low byte / word. These functions and their usage is as follows:

SWAPW(): Swap the low word and high word of the specified value.

int source = 0x12345678, result

SWAPW(source, result) //result == 0x56781234

SWAPB(): Swap the low byte and high byte of the specified value.

short source = 0x1234, result

SWAPB(source, result) //result == 0x3412
SWAPB(0x12345678, result) //result == 0x34127856

Being that your question is related to the formation of STRING data, I believe that you are most likely working with a char array. In that case, you can reassign each element within that array to a new “temp” char used within the OUTPORT. Here is an example:

char a[4] = "eTts"
char b[4] // Temp char variable

b[0] = a[1] // 'T'
b[1] = a[0] // 'e'
b[2] = a[3] // 's'
b[3] = a[2] // 't'

OUTPORT(b[0], "Free Protocol", 4) // will outport "Test" 

Thank you, that was exactly what I needed to get it working.

1 Like