5 ms·
The author claims that byte swapping code - "depends on integers being 32 bits long, or requires more #ifdefs to pick a 32-bit integer type." True. But you mi
by dlsym 15y ago
The author claims that byte swapping code
- "depends on integers being 32 bits long, or requires more #ifdefs to pick a 32-bit integer type."
True. But you might consider using inttypes.h which defines some pretty useful things like uint32_t (an unsigned 32 bit wide integer for example).
- "may be a little faster on little-endian machines, but not much, and it's slower on big-endian machines."
In fact swapping the byte order is _one_ CPU instruction.
You can for example use some inline assembly to optimize your code. (If your compiler fails to recognize this pattern.)
uint32_t byte_swap( uint32_t x )
{
asm( "bswap %0"
: "=g"(x)
: "0"(x)
);
return x;
}
Just my two cents...
- alexchamberlain 15y agoFor someone who hasn't written inline assembly, can you briefly explain what this does? ie what does =g mean?
- dlubarov 15y agoThe syntax is specific to GCC. "=g"(x) tells it that x is written by the assembly, so the compiler can't propagate an earlier value through the asm. The "g" means that the compiler can store x in a register, or in memory, etc. "%0" is replaced with "x" in the assembly. For details on the syntax: http://wiki.osdev.org/Inline_Assembly#Clobbered_Registers_List http://wiki.osdev.org/Inline_Assembly#Clobbered_Registers_Li...
- alexchamberlain 15y agoThis is architecture dependent ofc...
- masklinn 15y ago> In fact swapping the byte order is _one_ CPU instruction. That's one machine instruction, I'm pretty sure it's more than one microcode instruction ;)
- dfox 15y agoSwapping bits around is operation that is essentially free in hardware. It's just wires.
- ableal 15y agoMost hardware is just wires. Especially since transistors shrunk down to nearly nothing. Still, the layout of something like a barrel shifter (e.g. http://www.erc.msstate.edu/mpl/distributions/scmos/images/bshift.gif http://www.erc.msstate.edu/mpl/distributions/scmos/images/bs... , from a casual search) takes its space on die, much like an adder or multiplier. It's all wires and switches.
- pbsd 15y agoYes and no. On modern Intel CPUs, 32-bit bswap is 1 uop, but 64-bit bswap is 2. On AMD it seems to always be just 1 uop.
- mansr 15y agoOn most x86 and ARM CPUs, byte-reversing a register is a single-cycle operation. PowerPC has byte-reversing load and store instructions but lacks an instruction to reverse a register.
- mansr 15y agoThe operand constraint should be "r" since bswap works only on registers. You can also simplify it a little using an input/output operand: asm ("bswap %0" : "+r"(x)); That said, since version 4.5, gcc recognises the typical byte-swapping pattern and uses the appropriate CPU instruction.