in reply to Why does it return 0?

From the Perl Cookbook:

sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }

And your code is always returning zero because you declare $binnumb inside of the subroutine, thus resetting it every time it is called. At the last execution of the routine, $inNumb % 2 is zero.

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Re: Why does it return 0?
by mAineAc (Novice) on Feb 05, 2004 at 02:13 UTC
    Thank you Ovid, I was actually going to use this but I have to actually do it manually.
      If you want to know how conversion of numbers to a string works, try this:
      $num = 1234567; $result = ""; $base = 2; do { use integer; my $digit = $num % $base; substr($result, 0, 0) = $digit; # for any number < 10 $num /= $base; } while $num; print $result;
      If you like fixed width output, add enough zeros to the front, afterwards:
      substr($result, 0, 0) = "0" while length($result) < 32;

      If you want to play with $base > 10, for example hexadecimal , try:

      $num = 1234567; $base = 16; $result = ""; my @digit = (0 .. 9, 'A' .. 'Z'); do { use integer; my $digit = $num % $base; substr($result, 0, 0) = $digit[$digit]; # for base up to 36 $num /= $base; } while $num; print $result;

      Note that the do { ... } while $num; construct makes the loop execute at least once, so you get a proper result for zero.