Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: decimal to binary

by Gloom (Monk)
on Jan 23, 2001 at 21:44 UTC ( #53742=note: print w/replies, xml ) Need Help??


in reply to decimal to binary

Maybe you don't understand why I don't use pack/unpack... Only for illustrate the well known TIMTOWTDI :)
sub to_bin { my $num = shift; my $size = 0; my @result; while( $num >> $size ) { $size ++;} for (0..$size-1) { unshift @result , ( ($num & ( 2 ** $_ ) ) ? "1" : "0" ); } return join '' , @result ; }

Replies are listed 'Best First'.
Re: Re: decimal to binary
by Gloom (Monk) on Jan 25, 2001 at 01:04 UTC
    I'm working on it and I have found shortest way to do that
    sub to_bin { my( $num , $len ) = ( shift , 0 ); while( $num >> $len ){ $len++ ;} return reverse map {( $num & 1 << $_ ) ? "1" : "0";}(0..$len-1); }
    did someone can do better ? ( I'm sure you can, I trust in you ;)
      Another WTDI.

      A one liner (I'm no true obfuscator):
      perl -ne 'undef@_;while($_){$_[0]=($_&1&&1||0).$_[0];$_>>=1}print"@_\n"'

      Or a more sensible sub version with the same logic.

      sub to_bin { my $num = shift; my $ret = ''; while ($num) { $ret = (($num % 2) ? 0 : 1) . $ret; $num >>= 1; } return $ret; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (1)
As of 2022-01-20 03:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (56 votes). Check out past polls.

    Notices?