I have 4 bytes of data read in from a binary file. I need to treat this data as an 'int' in C, and get it's binary value. Perl wants to treat it as four characters, however. Is there any simple way to treat it as an integer, or convert it to an integer? Right now I have the painfully long:
sub BinWordToDec { # There's GOT to be a better way to do this conversion.... # Converts a 32 bit binary word to a decimal integer. my $val = $_[0]; my $temp = "0b$val"; print "temp: $temp\n"; unless (length $val == 4) {return -1} my $bit1 = ord (substr $val,0,1); my $bit2 = ord (substr $val,1,1); my $bit3 = ord (substr $val,2,1); my $bit4 = ord (substr $val,3,1); $bit1 = unpack("B*", pack("N", $bit1)); $bit2 = unpack("B*", pack("N", $bit2)); $bit3 = unpack("B*", pack("N", $bit3)); $bit4 = unpack("B*", pack("N", $bit4)); my $dec = substr("0" x 8 . $bit1, -8).substr("0" x 8 . $bit2, -8). substr("0" x 8 . $bit3, -8).substr("0" x 8 . $bit4, -8); my $int = unpack("N", pack("B32", $dec)); $dec = sprintf("%d", $int); print "Decimal: \n", $dec, "\n"; return $dec; }
Thanks

Originally posted as a Categorized Question.


In reply to How do I convert a 32 bit unsigned integer to its decimal value? by notfred

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.