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

I'm seeking a better way to do this... I've read in a string of binary data into $string.
my $number = undef; if( $string =~ m/(.)(.)/ ) { $number = hex( unpack("H*", "$2$1") ); }

Now, there has got to be a better way to do that. Please help?

Replies are listed 'Best First'.
Re: hex(unpack("H*")) help?!?!
by Thelonius (Priest) on Oct 31, 2002 at 17:14 UTC
    If the input data is in network (big-endian) order, do this:
    $number = unpack("n", $string);
    If it's in little-endian order, do this:
    $number = unpack("v", $string);
    If it's in the order for the machine your perl is running on, you can do this:
    $number = unpack("S", $string);
    Or use a little 's' if you want signed data.
      doh, it was right there all along... in perldoc -f pack I mean. God bless you. Thank you. May you live a 1,000 years... :)
Re: hex(unpack("H*")) help?!?!
by davorg (Chancellor) on Oct 31, 2002 at 17:07 UTC
      Nope, that converts the string in the wrong byte order. that won't work at all. Note that '$1' and '$2' were bytes from a file, not integers from a file?

        Ah. OK. Is the string always two chars long?

        $number = hex("0x". reverse $string);

        (please don't take this suggestion seriously)

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

        I also checked... presuming the $string was "6801" instead of "\x68\x01" to see if it would work anyway... it does not. try it...
        perl -e '$i = hex("0x6801"); print sprintf("\%x", $i), "\n"'
        Still wrong. It should return 168, not 6801