Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

pack and unpack trouble

by scoobyrico (Beadle)
on Dec 22, 2011 at 16:13 UTC ( #944804=perlquestion: print w/ replies, xml ) Need Help??
scoobyrico has asked for the wisdom of the Perl Monks concerning the following question:

I have been tasked to convert some C# code to Perl. I think I need pack and unpack and I am having some trouble understanding them well enough. I have read the tutorial and have worked though some of the examples, but still I am unable to get the right results.

The are where I have not been able to get right is with the byte casting of the result of the ^ operand. When I print out $mRc ^ $byte I get 4294965887 which I need to be 127.

Perl Code
$mPolyTable[(unpack "V", pack "U4", ($mCrc ^ $byte))] ;
C# code
mCrc = mPolyTable[(byte)(mCrc ^ iByteArray[x])];
Any help would be greatly appreciated.

Comment on pack and unpack trouble
Select or Download Code
Re: pack and unpack trouble
by ikegami (Pope) on Dec 22, 2011 at 16:28 UTC
    $mCrc = $mPolyTable[ ( $mCrc ^ $iByteArray[$x] ) & 0xFF ];

    The closest pack equivalent to a (byte)val would be

    unpack('C', substr(pack('J', $val), 0, 1))

    or

    unpack('C', substr(pack('J', $val), -1, 1))

    depending on your machine. That could be made portable as

    unpack('C', substr(pack('J<', $val), 0, 1))

    which simplifies to

    unpack('C', pack('J<', $val))

    But what a waste.

    Update: Added the content underneath the bar.

      Excellent! as a follow up, if I want to take 1365238130 to 515FE172? Upate: I would have thought it was hex(1365238130) but that gets me 83301204272. So clearly I am doing something wrong.
      In C#
      uint temp = 1365238130; System.Console.WriteLine(temp.ToString("X"));
        Adapted from perlfaq4: How do I convert between numeric representations/bases/radixes?
        my $hex_string = sprintf '%X', 1365238130;

        hex converts *from* hex to a number.

        sprintf '%X', $n will represent a number using hex.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://944804]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2014-09-23 14:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (222 votes), past polls