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

I have some code that is pulling appart a file and is using unpack with a 'n' conversion to extract what should be a 16 bit signed big endien number. I'm getting an unsigned result. Is that expected behaviour?

The following code demonstrates the issue:

use strict; use warnings; print "Network (16 bits) pack/unpack: ", unpack ('n', pack ('n', -1)), + "\n"; print "Short pack/unpack: ", unpack ('s', pack ('s', -1)), "\n"; print "Network (32 bits) pack/unpack: ", unpack ('N', pack ('N', -1)), + "\n"; print "Long pack/unpack: ", unpack ('l', pack ('l', -1)), "\n"; print "Network (cvt) pack/unpack: ", unpack ('s', pack ('s', unpack (' +n', pack ('n', -1)))), "\n";

Prints:

Network (16 bits) pack/unpack: 65535 Short pack/unpack: -1 Network (32 bits) pack/unpack: 4294967295 Long pack/unpack: -1 Network (cvt) pack/unpack: -1

This is using AS Perl 5.8.7 (813) on XP.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re: Unexpected Network conversion behaviour for unpack
by Corion (Patriarch) on Feb 09, 2006 at 23:12 UTC

    I think that nNvV return unsigned results:

    n An unsigned short in "network" (big-endian) order. N An unsigned long in "network" (big-endian) order. v An unsigned short in "VAX" (little-endian) order. V An unsigned long in "VAX" (little-endian) order.
      This appears to be a fix in perlfunc, the older version on this site doesn't mention "unsigned" anywhere:
      n A short in "network" (big-endian) order. N A long in "network" (big-endian) order. v A short in "VAX" (little-endian) order. V A long in "VAX" (little-endian) order. (These 'shorts' and 'longs' are _exactly_ 16 bits and _exactly_ 32 bits, respectively.)

      Damn, I think I'll throw the Camel in the bin. It and the Perl Pocket Reference just say words to the effect that: n Short in network (big endien) order.

      Thanks for that. I should have looked at perlfunc earlier, I'd have saved a couple of hours!


      DWIM is Perl's answer to Gödel