0

Possible Duplicate:
How do I convert between big-endian and little-endian values in C++?

I was wondering how you would byte swap a 32-bit word

I have a huge buffer of these words and each of them need to be byte swapping due to endianness.

0

2 Answers 2

6

Either use the functions provided by your OS (cf. Martin Beckett's answer), or alternatively, if you are looking for a way to do this out of interest you may be interested in the following code snippet:

x = (x & 0x0000FFFF) << 16 | (x & 0xFFFF0000) >> 16; x = (x & 0x00FF00FF) << 8 | (x & 0xFF00FF00) >> 8; 
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, to complete the byte swapping a second line is needed: x = (x & 0x00FF00FF) << 8 | (x & 0xFF00FF00) >> 8;
@bames53 Yes, you're right! Sorry about that!
0

Use htonl / ntohl provided by your OS

3 Comments

That will only swap bytes if the native format is the reverse of network format.
@MikeSeymour true, but it's most likely that this is what the user needs. Anyone writing some low level non-network order driver is likely to know how to do it anyway. This seemed a good 99% answer
Well actually I am writing a low level non-network order driver... For an internship though so its above my head. I understand the concept but I am used to high level languages.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.