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

Hello,

I would like to be able to output, to STDOUT and/or to file, an integer in it's raw form, in 32 bit, not the string representation of the integer.

eg, I have an integer equal to 24 decimal.

I want output to be:

0x00000018

not

0x3234 ie, "two four"

help?

Replies are listed 'Best First'.
Re: output binary data
by roboticus (Chancellor) on Dec 29, 2010 at 03:56 UTC

    Allasso:

    You can use the pack function to create a binary value in a scalar variable, and then write it to the output file. Be sure to use binmode on the file handle so that it won't modify the binary values you send. Something like:

    use strict; use warnings; my $foo = 12345; $foo = pack "l", $foo; open my $FH, '>', "foo.bin"; binmode($FH); print $FH $foo; close $FH;

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      You probably are aware of this but "32-bit integer" could mean different things.

      It could be either signed or unsigned or you may want (for networking purposes) use a different endianess (is that a word?) than the one your architecture uses.

      Happily pack provides "l", "L", ,"N", and "V" to cater for all your needs as long as you know what you need.

Re: output binary data
by oko1 (Deacon) on Dec 29, 2010 at 06:07 UTC

    Just to add a little "decoration" to roboticus' answer :) - you might also want to display a string representation of what you're saving, i.e.

    printf STDERR "0x%08x\n", $integer;
    -- 
    Education is not the filling of a pail, but the lighting of a fire.
     -- W. B. Yeats

      thanks for the usual great help, dear monks.

      I don't think binmode is necessary on a unix machine.

      Now maybe someone can tell me how I reply to my original post, without branching off someone else's...

      BTW, that "three two" was supposed to be "two four" :-)

        Allasso:

        While it's true that binmode isn't required on a unix box, nowhere in the OP did you mention unix. Using binmode can help portability, so I mentioned because you (or a reader solving a similar problem) might have been using Windows or other OS that may need it.

        As for replying to your own node, I see that the "Comment on" link is below the update section, so I imagine that you'd just click it as for any other node. (Not intending to be snarky, I almost missed it when I looked for it too. I was expecting it to be above the update stuff.)

        ...roboticus

        When your only tool is a hammer, all problems look like your thumb.

Re: output binary data
by Allasso (Monk) on Dec 30, 2010 at 00:25 UTC

    ...as usual, I look and look and look, and then I find the answer just seconds after I post.

    disregard the thing about replying to the op :-)

    (I tried posting this this morning but lost internet...)