| re: Question about shifting return values
* Hannes Allmaier:[color=blue]
>
> I found interesting code in a Visualc++-file (all variables are unsigned
> integers)
>
> return (CurrentBfr << (32 - BitsLeft)) >> (32 - N);;
>
> so it seems the return value gets right shifted (32-N) times, like this
>
> return(CurrentBfr << (32 - BitsLeft))>> (32 - N);[/color]
The only difference is the null statement (the semicolon) in the first
example.
[color=blue]
> Interesting that this actually works, however even more interesting why
> my simplification
>
> return(CurrentBfr>>(Bitsleft-N));
>
> doesn't work. If a left shift corresponds to a multiplication and a
> right shift to a division by 2, this should be ok.[/color]
First, a shift operation discards information, the bits shifted out of
the value representation. For numbers that are small enough that
doesn't matter wrt. left shift n bits, because the bits shifted out then
don't change the numeric value from what you'd get by multiplying with
2^n. For larger numbers it does matter, so on that count alone your
simplification wouldn't work in all cases.
Second, the result of a C++ shift operation is undefined if the right
operand is negative, so 'x<<n' is not equivalent to 'x>>-n', which your
simplification relies on.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail? |