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.

Community
  • 1
  • 1
user1496413
  • 33
  • 1
  • 1
  • 4

2 Answers2

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;  
Thomas Russell
  • 5,870
  • 4
  • 33
  • 68
0

Use htonl / ntohl provided by your OS

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • 5
    That will only swap bytes if the native format is the reverse of network format. – Mike Seymour Jul 09 '12 at 14:40
  • 1
    @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 – Martin Beckett Jul 09 '12 at 14:41
  • 3
    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. – user1496413 Jul 09 '12 at 16:04