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

Wise Monks,
I have just come across a problem which I could not solve for a while. Ad rem, here is the script:

perl -e '$a = 127; printf "original:%04x, bit-negative version:%04x\n", $a, ~$a;'

which produces some output, i.e:

original:007f, bit-negative version:ffffff80

However I would like to receive a bit different one:

original:007f, bit-negative version:ff80

Having searched throughout the monastery, I have found a hint which lead me to write a better script hint:

perl -e '$a = 127; $b = pack S, ~$a; $b = unpack S, $b; printf "%X, %X\n", $b, ~$a;'

My questions is if there is a more friendly way of casting/formatting numbers in Perl? Like (casting) I know from C.

Replies are listed 'Best First'.
Re: Casting numbers
by matija (Priest) on Apr 07, 2004 at 15:58 UTC
    You bit-negated a 32 bit value - of course printf gave you all the significant digits. Only you can know which digits are safe to throw away.

    I recommend the following:

    perl -e '$a = 127; printf "original:%04x, bit-negative version:%04x\n" +, $a, (~$a)&0xffff;' original:007f, bit-negative version:ff80
Re: Casting numbers
by Abigail-II (Bishop) on Apr 07, 2004 at 16:49 UTC
    $ perl -we 'printf "%04x\n" => unpack "S" => ~ pack "S" => 127' ff80

    Abigail

Re: Casting numbers (^)
by tye (Sage) on Apr 07, 2004 at 18:41 UTC

    You can replace ~$a with $a^0xffff (or $a^0xff for byte-wise bit negation).

    - tye