http://www.perlmonks.org?node_id=970912

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

After I read in a string from a file, how do I get the numeric value?

(1 << 18) | (0x00 << 12) | (0x00 << 6) | 0x00

I believe the correct value should be 0x40000. Tired of guessing my way thru...

Replies are listed 'Best First'.
Re: Convert bitwise value to its value
by sauoq (Abbot) on May 16, 2012 at 21:48 UTC

    And if you don't trust the input, you can use the same technique more Safely like so:

    #!/usr/bin/perl use warnings; use strict; use Safe; my @ops = qw( padany leaveeval lineseq bit_or left_shift const left_shift right_shift bit_and bit_xor bit_or negate i_negate not complement); my $safe = Safe->new(); $safe->permit_only(@ops); my $result = $safe->reval( '(1 << 18) | (0x00 << 12) | (0x00 << 6) | 0 +x00' ); printf "0x%x\n", $result;

    -sauoq
    "My two cents aren't worth a dime.";
Re: Convert bitwise value to its value
by mbethke (Hermit) on May 16, 2012 at 20:24 UTC
    If you trust the input to contain nothing evil, eval will do:
    $s = "(1 << 18) | (0x00 << 12) | (0x00 << 6) | 0x00"; printf "0x%x\n", eval $s;
Re: Convert bitwise value to its value
by AnomalousMonk (Archbishop) on May 17, 2012 at 03:40 UTC

    ... and there's also a programmers calculator, such as the app supplied standard with Windoze. I assume there is something similar in *nix.