Re: Swap two integers without using temporary variable
On Nov 29, 7:21 pm, Joe Greer <jgr...@doubletake.com> wrote:
Kai-Uwe Bux <jkherci...@gmx.net> wrote
After all, many compilers detect quite some idioms. For example
compilers detect that something like "a = (a << 8) | (a >> 24);"
is actually a rotation and compile that as one single opcode.
That's because such an expression is *always* a rotation.
old C books say that it is shift,is the behavoir changed since then?
I thaught a << 8 is a shift and a >> 24 is a shift. So,
( a << 8 ) | ( a >> 24 )
would be a rotation assuming a bitlength of 32.
Yes. I just sort of assumed that (and that everyone else would,
since it seems so obvious).
I don't know about now, but in the olden days, << always 0
filled and >> was machine dependent.
It depends on the type. As a general rule, I only use shifts
and bitwise operators on unsigned types, so there are no
Juha's expression is wide-spread, and is the idiomatic way to
express a rotation in C/C++. It would, I believe, be
immediately recognized as a rotation by anyone who has worked on
code where rotations were needed. (It's used in the reference
implementations of MD5 and SHA1, for example.)
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34