Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Bit by a Hex String

by Abigail-II (Bishop)
on Aug 29, 2003 at 15:08 UTC ( #287694=note: print w/replies, xml ) Need Help??


in reply to Re^2: Bit by a Hex String
in thread Bit by a Hex String

Here's a Math::BigInt solution.
#!/usr/bin/perl use strict; use warnings; use Math::BigInt; $_ = "DEADBEEFBABEFACE1234567890"; my $num = Math::BigInt -> new (0); # Convert the number to a Math::Int decimal number. while (length) { my $chunk = substr $_, 0, 4, ""; $num *= 2 ** (4 * length $chunk); $num += hex $chunk; } # Multiply by 2, add 1. $num *= 2; $num += 1; # Convert the Math::BigInt number to hex. my @a; while ($num) { push @a => sprintf "%X" => $num % 16; $num /= 16; } my $new = join "" => @a; print $new, "\n";

And here's an Inline::BC solution:

#!/usr/bin/perl use strict; use warnings; use Inline 'BC'; print x("DEADBEEFBABEFACE1234567890"); __DATA__ __BC__ ibase = 16 obase = 10 define x (a) { return (a * 2 + 1) }

Abigail

Replies are listed 'Best First'.
Re: Re: Bit by a Hex String
by abitkin (Monk) on Aug 29, 2003 at 15:29 UTC
    Okay, first I need to say, I love your BC solution. It's simple, and elegant. That being said I did some playing around with BigInt, so here's the code I came up with:
    sub shift_bs{ $add = shift; $source = shift; $num1=Math::BigInt->new("0x".$source); $num1->blsft(1); $num1+=$add; $temp = $num1->as_hex(); $temp =~ /0x(.*)/; return $1; }
    Yeah, the $add is a legacy thing, but that's okay. I want to thank you especially, because you went to quite a bit of work to come up with that code.
    ==
    Kwyjibo. A big, dumb, balding North American ape. With no chin.
      $num1=Math::BigInt->new("0x".$source);

      Ah, I didn't know you could do that. The Math::BigInt manual page says:

      Input Input values to these routines may be either Math::Big- Int objects or strings of the form "/^[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/".

      Abigail

        Neither did I

        I only tried it after seeing this in the documentation:

        Examples for converting: my $x = Math::BigInt->new('0b1'.'01' x 123); print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";

        ==
        Kwyjibo. A big, dumb, balding North American ape. With no chin.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2020-07-07 12:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?