How to swap bytes ?

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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

'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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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.
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...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.