Spooky has asked for the wisdom of the Perl Monks concerning the following question:

How would it be possible, or would it be possible, to arrive at a -1 with Perl given the hex string: 'ffffffffffffffff'. I was able to arrive at the large integer value this is equal to but output I'm looking at actually produced (or maybe it was somehow forced) a -1?

Replies are listed 'Best First'.
Re: -1 from hex ffffffffffffffff ?
by almut (Canon) on Oct 02, 2009 at 15:57 UTC
    $ perl -e"print unpack('q',pack('H*', 'ffffffffffffffff'))" -1

    See pack  (and Two's complement for background).

    (The 'q' stands for a 64-bit value, but you'd also get -1 for any other signed int of shorter length, such as 'l' (32-bit), 's' (16-bit), 'c' (8-bit) — in which case only part of the bit pattern would be used in the unpack...)

      That should be q> (big-endian byte order), not q (native byte order).

      Furthermore, it would be better to pad out the hex number in case fewer than 16 digits are provided.

      sub hex_to_signed_quad { return unpack 'q>', substr(('0'x16).$_[0], -16); }
        should be q> (big-endian byte order)

        Well, no one said in what order the ffffffffffffffff is to be interpreted, and in this special case of all bits being ones, it wouldn't make much of a difference anyway :)

      ..thanks so much!
Re: -1 from hex ffffffffffffffff ?
by Marshall (Canon) on Oct 02, 2009 at 16:07 UTC
      ...thanks for the info!