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.

7
  • 6
    Is this bottleneck? Commented Jan 6, 2015 at 9:53
  • 2
    I would expect that the htonl resp. ntohl (depending on your platform) macro definition of your compiler would be optimal, cf. linux.die.net/man/3/ntohl Commented Jan 6, 2015 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). Commented Jan 6, 2015 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: stackoverflow.com/a/105371/253056 Commented Jan 6, 2015 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. Commented Jan 6, 2015 at 10:10

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

I think it's htonl/ntohl for 32 bits.
@PeterSchneider Thanks, I mistyped short versions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.