How to swap bytes ?

naseeam used Ask the Experts™
I read a word from modbus register.  I need to swap the bytes:

i.e.  I read   0x0003

I need to swap them so result would be     0x0300

Please provide a software instructions to achieve this.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012
'ntohs()' ( would do that. Or, if you'd prefer to do that manually:

#define swap_bytes(x) ((((uint16_t)(A) & 0xff00) >> 8) | (((uint16_t)(x) & 0x00ff) << 8))

Open in new window

Top Expert 2009

Note that ntohs would only work if the host byte order is different from the network byte order (ie. the host byte order is little endian) - otherwise it's a noop.
Top Expert 2012

I was not too unsure in assuming that the host platform was Intel ;o)

And for the case that it's not, I added the implementation...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial