2

I need to swap bytes of a 32 bit value 11223344 should be swapped as 44332211. Currently i'm using following logic.

val = ((((val) & 0xff000000) >> 24)|
      (((val) & 0x00ff0000) >>  8) |
      (((val) & 0x0000ff00) <<  8) |
      (((val) & 0x000000ff) << 24));

This is working as expected. But i just wanted to know is there any other fastest/Optimized way to do the same.

Chinna
  • 3,930
  • 4
  • 25
  • 55
  • 6
    Is this bottleneck? – Mohit Jain Jan 06 '15 at 09:53
  • Yes... This code called frequently. a slight Change in this code will effect the performance drastically. – Chinna Jan 06 '15 at 09:54
  • 2
    I would expect that the htonl resp. ntohl (depending on your platform) macro definition of your compiler would be optimal, cf. http://linux.die.net/man/3/ntohl – Peter - Reinstate Monica Jan 06 '15 at 10:00
  • 1
    Any 'optimized' C code you may end up using makes your code highly dependant on your particular C compiler (and the version of it) and the optimizations it implements. If you find that you need the fastest way I'd suggest writing the code in assembler (e.g. the `bswap` x86 instruction which does exactly what you want). – Frerich Raabe Jan 06 '15 at 10:04
  • 2
    For x86 you can do this in a single instruction, BSWAP - use compiler intrinsics or inline asm to do this from C code. See: http://stackoverflow.com/a/105371/253056 – Paul R Jan 06 '15 at 10:05
  • 2
    byteorder.h in my cygwin gcc 4.8.3 uses bswap for ntohl/htonl unless the argument is a compile time constant (in which case the value is computed at compile time with bit shifts). Again, the thing to do is use proven prior art. – Peter - Reinstate Monica Jan 06 '15 at 10:10
  • 1
    If it's called frequently, you'd better organize your code to pass big chunks of contiguous data (DOD) to convert at time. You'll see a significant speed-up and the compiler will be able to perform more optimizations on it. – edmz Jan 06 '15 at 10:27

1 Answers1

0

If htonl and ntohl functions are available and suit your needs, you may consider using it. Otherwise search for a variety of methods, profile those and choose the quickest one. Also try for any compiler provided function __builtin_bswap32 in gcc for example.

One example taken from here with light modification.

register uint32_t value = number_to_be_reversed;
uint8_t lolo = (value >> 0) & 0xFF;
uint8_t lohi = (value >> 8) & 0xFF;
uint8_t hilo = (value >> 16) & 0xFF;
uint8_t hihi = (value >> 24) & 0xFF;

uint32_t value = (hihi << 24)
               | (hilo << 16)
               | (lohi << 8)
               | (lolo << 0);
Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100