Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: String to Hex

by GrandFather (Saint)
on May 22, 2007 at 21:08 UTC ( #616872=note: print w/replies, xml ) Need Help??

in reply to String to Hex

The problem is that the number is too big to be represented as a 32 bit integer and your Perl has been compiled to use 32 bit integers.

For positive integers you can use:

use strict; use warnings; use bigint; my $num = 24600988483; my @parts; while ($num) { unshift @parts, $num & 0xFFFFFFFF; $num /= 0x100000000; } printf "%x", $_ for @parts;



Update: jettero's solution is much cleaner!

Update: Unstruck on advice ;)

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: String to Hex
by shmem (Chancellor) on May 22, 2007 at 21:14 UTC
    But yours is nice too, and clean also. You mustn't be ashamed and strike through :-)


    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: String to Hex
by blazar (Canon) on May 22, 2007 at 22:24 UTC
    Update: Unstruck on advice ;)

    I also agree that it deserved being unstruck. But:

    • I would $num >>= 32;
    • AIUI from earlier posts by knowledgeable people, the technique is valid for numbers such that the loop will always involve one or at most two iterations of the loop.

    Update: s/16/32/ applied above, thanks GF.

      I would $num >>= 16;

      Both methods have problems on 32-bit systems.

      GrandFather's produces the correct result and warnings, but yours gives the wrong result?

      print 24600988483 / 2**32;; 5.72786398301832 print 24600988483 / 0x100000000;; Integer overflow in hexadecimal number at (eval 24) line 1 Hexadecimal number > 0xffffffff non-portable at (eval 24) line 1 5.72786398301832 print 24600988483 >> 16;; 65535

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Warnings? With AS Perl 5.8.7 I see no warnings with either the code I posted or with the (corrected) $num >>= 32; variant suggested by blazar. You did use bigint; didn't you?

        DWIM is Perl's answer to Gödel

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://616872]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2022-01-22 18:34 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (63 votes). Check out past polls.