How to swap bytes ?

naseeam
naseeam used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012
Commented:
'ntohs()' (http://linux.die.net/man/3/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

Commented:
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.
jkr
Top Expert 2012

Commented:
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