develooper Front page | perl.perl5.porters | Postings from March 2008

Re: left_shift problem

Thread Previous | Thread Next
Yitzchak Scott-Thoennes
March 24, 2008 13:13
Re: left_shift problem
Message ID:
On Mon, March 24, 2008 5:22 am, Reini Urban wrote:
> Take some number between LONG_MAX and ULONG_MAX.
> I have 64bitints, so
> $ perl -Dx -e'my $uv=9223372036854775807*2; print $uv," ",($uv>>1)," ";
> {use integer; print $uv, " ",$uv >> 1}'
> ...
> 18446744073709551614 9223372036854775807 18446744073709551614 -1
> use integer => $^H=1, => op_private=1, so the right_shift took the uv as
> iv (highest bit as sign), then shifted it SETi(i >> shift);
> and lost it.

The high bit wasn't lost, it's still there, shifted into the 2**62
position. And because >> under use integer does sign extension, the
sign bit is set also.  The >> not under use integer doesn't do sign
extension, so ends up with the sign bit off:

$ perl -we'my $uv = 0x80000000; printf  "%032b %032b\n", $uv,($uv>>1);
{use integer; printf "%032b %032b\n", $uv,$uv >> 1}'
10000000000000000000000000000000 01000000000000000000000000000000
10000000000000000000000000000000 11000000000000000000000000000000

> This can be avoided and actually is avoided in all lisp's - because with
> "(the integer ...)" local type declaration, it is upgraded to an
> unsigned, if the signed cannot hold it. Not talking about bignums.
> But should it be avoided in perl with use integer?
> My common sense would yes, because bit operations as common integer
> arithmetic are usually enforced with use integer, and they should cleary
> work as UV. Or fix the docs of use integer, to tell the truth about
> downgrading UV's to IV's when doing bitops with use integer.

But the docs about 'use integer' are already clear that it means 'use
signed integer' (in particular, 'use IV').  IMO, this is really a
fundamental part of the pragma, and apparently a major difference from
the lisp feature you show.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About