Re: [Dev-C++] Convert Little-Endian to Big-Endian (and vice versa)
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Daniel K. O. <dan...@ya...> - 2004-11-11 18:37:26
|
Joey Dala wrote:
> Does anybody know a faster algorithm to swap the bytes
> of an 'unsigned long' than this:
>
> // SWAP 32-BITS
> #define SWAP_LONG( A ) ((A << 24) | ((A & 0xff00L) << 8 ) | ((A &
> 0xff0000L) >> 8 ) | ((unsigned long)A >> 24))
Faster than this? Only if you use architecture-specific instructions.
The 486 (and higher) family has the "bswap" instruction. Here's an example:
---
#include <stdio.h>
#define SWAP32(x) asm volatile ("bswap %0" : "=r" (x) : "0" (x))
int main(void)
{
int foo = 1;
printf("%08x\n", foo);
asm volatile (
"bswap %0"
: "=r" (foo)
: "0" (foo)
);
printf("%08x\n", foo);
SWAP32(foo);
printf("%08x\n", foo);
getchar();
return 0;
}
---
Notice the use of the extended assembly syntax, so GCC can perform
better optimizations around the asm beast.
Also, the "volatile" keyword to make sure GCC won't move the assembly
statement around in the optimization proccess.
Before you ask, some information about using AT&T assembly syntax and
extended syntax is available here:
http://www.delorie.com/djgpp/doc/brennan/brennan_att_inline_djgpp.html
Daniel K. O.
|