⭐ in reply to How do I convert between decimal and binary?
To turn a perl integer into a binary string we must first pack it into network byte order which the "N" format stands for. Then we unpack it into the "B32" format. We then strip off all leading 0's with a simple substitution.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))); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Answer: How do I convert between decimal and binary?
by I0 (Priest) on Dec 19, 2000 at 17:06 UTC | |
by Anonymous Monk on Apr 05, 2013 at 04:42 UTC | |
by Anonymous Monk on Sep 11, 2004 at 14:31 UTC | |
by ysth (Canon) on Sep 12, 2004 at 06:48 UTC |