In article <11**********************@z14g2000cwz.googlegroups .com>,
vib <vi*****@gmail.com> wrote:
Are you refering to the statement, "I decide not to use OR with
(CHAR_BIT-1). "? Just think that shifting (CHAR_BIT -1) bits to the
left is less efficient comparing to an if instruction.
You can precalculate the value 1 << (CHAR_BIT-1)
and multiply (ar[i-1] & 1) by that precalulated value.
That would transform the code from a "shift by a known factor of
an unknown bit value" into a "multiply an unknown bit by a constant
value".
Your code needs CHAR_BIT if it is to be portable. You should not
be assuming 8 bits per unsigned char.
Another approach would be to | in (ar[i-1] & 1) ? 1 << (CHAR_BIT-1) : 0
The 1 << (CHAR_BIT-1) will be computed at compile time .
This trades the multiply (or shift) into a conditional computation.
On some systems a ?: construct with constants for both potential
results can be done -quite- efficiently, but on other systems it
requires a full conditional branch that messes up pipelining and
so on.
On systems (e.g., MIPS R10000 chips) that have the
"move conditional" instruction, the ?: approach would be most efficient.
On many systems, most efficient would be the shifting of the bit
by (CHAR_BIT-1) -- but there are some important CPUs that have no
"barrel shifter" that can do it in one step, and there are some
CPUs on which there is an effecient shift in one direction but not the
other, so the efficiency of shifts should not be taken for granted.
On systems without an efficient shift instruction, the version
using the integer multiply by a constant might be the most efficient,
but this is not certain either... some systems do integer multiplies
quite efficiently, others only do floating point multiplies efficiently.
On a fair number of CPUs, if/then/else is the least efficient choice.
But even that is quite variable, even within the same machine:
if the instructions are all in primary cache the if/then/else
might be pretty efficient, but if the instructions are not in
primary cache then the if/then/else might come out as the slowest...
Still, it's a good rule of thumb that a conditional
branch ( ?: or if/then/else ) will -likely- be slower than
using short code that can compute the value without using a branch.
--
Warning: potentially contains traces of nuts.