Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

convert each character of a string to number

by Lowry76 (Novice)
on Feb 12, 2017 at 03:26 UTC ( #1181779=perlquestion: print w/replies, xml ) Need Help??
Lowry76 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all I'm looking for a fast way of converting a sequence of four characters (a,b,c,d) to a number. So far I use

my $lt = []; $lt->[ord(a)] = 00; $lt->[ord(b)] = 01; $lt->[ord(c)] = 10; $lt->[ord(d)] = 11; foreach my $string{ _convert($string); ... sub _convert{ my $string = shift; my $bs=""; foreach(split(//,$string)){ $bs.=$lt->[$_]; } return int($bs); }
I also tried using a hash of form {a=>00,b=>01,c=>10,d=>11} or use four substitutes on $string which should have been kind of four times the runtime (processing the complete string 4 times). But somehow the regexp substitution seems to be the fastest. However, it's still pretty slow if I'm iterating over millions of strings. Any faster solution? Cheers, Lowry

Replies are listed 'Best First'.
Re: convert each character of a string to number
by tybalt89 (Hermit) on Feb 12, 2017 at 04:04 UTC

    try:

    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1181779 use strict; use warnings; sub convert { unpack('H*', shift() =~ tr/cd/qr/r) =~ tr/1267/0101/r; } for ( qw( abcd dcba abab cdcd abba caab ) ) { print "$_ -> ", convert($_); }

    prints:

    abcd -> 00011011 dcba -> 11100100 abab -> 00010001 cdcd -> 10111011 abba -> 00010100 caab -> 10000001

      Hi tybalt89,

      Very clever :-)

      Building on your idea, this appears to be a bit faster: $string=~tr/abcd/\x00\x01\x10\x11/; unpack('H*', $string);

      Regards,
      -- Hauke D

Re: convert each character of a string to number
by kcott (Canon) on Feb 12, 2017 at 06:00 UTC

    G'day Lowry76,

    Is this the type of thing you're looking for?

    $ perl -e 'printf "%02b", ord($_) - ord("a") for split //, "abcd"' 00011011

    — Ken

Re: convert each character of a string to number
by poj (Prior) on Feb 12, 2017 at 16:00 UTC

    Consider building a hash of all 256 possible strings.

    #!/usr/bin/perl use strict; my %convert=(); my %char = ( '00'=>'a', '01'=>'b', '10'=>'c', '11'=>'d', ); for my $n (0..255){ my $bin = sprintf "%08b",$n; (my $str = $bin) =~ s/(..)/$char{$1}/eg; $convert{$str} = int $bin; } for ( qw( aaaa abcd dcba abab cdcd abba caab dddd) ){ print $_.' '.$convert{$_}."\n"; }
    poj

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1181779]
Approved by Athanasius
Front-paged by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2017-03-30 00:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (353 votes). Check out past polls.