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

Re(golf): I'm looking for the faster way to convert char 2 Bin and Bin 2 char (8bits)

by jynx (Priest)
on Jan 27, 2001 at 03:17 UTC ( #54673=note: print w/ replies, xml ) Need Help??


in reply to I'm looking for the faster way to convert char 2 Bin and Bin 2 char (8bits)

beware before!

Yesterday i found an amusing little routine to do decimal to binary (not the same drek everyone did in school as i understand it). So i converted it to perl and felt like posting it. Unfortunately i may have messed up something, so if someone (like maybe IO) could tell me if i did or not that would be sweet.

sub dec2bin { my $num = shift; my @num; my $i = 0; (push @num, (($num & 2**$i) == 2**$i) ? 1 : 0) and $i++ until (2**$ +i > $num); return 0 + join '', reverse @num; }
It is completely untested, but it should work (as if that's any boon to a programmer)

jynx

update: changed the $n to $num on line 5 according to IO's suggestion (thank you).


Comment on Re(golf): I'm looking for the faster way to convert char 2 Bin and Bin 2 char (8bits)
Select or Download Code
Replies are listed 'Best First'.
Re: Re(golf): I'm looking for the faster way to convert char 2 Bin and Bin 2 char (8bits)
by I0 (Priest) on Jan 27, 2001 at 05:08 UTC
    Testing it would have found
    Name "main::n" used only once: possible typo at - line 5.
    But besides that, ** is a more expensive operation than you need here especially doing it 3 times per iteration.
    using 1<<$iin place of 2**$i would be a bit faster.
    my $i = 1; (push @num, (($num & $i) ? 1 : 0)) and $i<<=1 until $i > $num;
    is even better. And
    (push @num, (($num & 1) ? 1 : 0)) and $num>>=1 until 1 > $num;
    still faster...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2015-07-31 01:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls