thanos1983 has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I am trying to convert decimals to binary and binary to decimals. By using pack and unpack I can convert all positive numbers, in case that a number is negative the process needs to be changed.
Update: Solution with pack and unpack at the end of the question.Sample of working code demonstrating the problem:
#!/usr/bin/perl use strict; use warnings; my $possitive = 3; my $negative = -3; print "My possitive decimal: ".$possitive."\n"; print "My negative decimal: ".$negative."\n"; my $possitive_b = dec2bin($possitive,8); my $negative_b = dec2bin($negative,8); print "Possitive binary: ".$possitive_b."\n"; print "Negative binary: ".$negative_b."\n"; my $possitive_d = bin2dec($possitive_b); my $negative_d = bin2dec($negative_b); print "Possitive_binary back to decimal: ".$possitive_d."\n"; print "Negative_binary back to decimal: ".$negative_d."\n"; sub dec2bin { my $bits = shift; my $possition = shift; my $str = unpack("B32", pack("N", $bits)); $str = substr $str, -$possition; return $str; } sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } __END__ My possitive decimal: 3 My negative decimal: -3 Possitive binary: 00000011 Negative binary: 11111101 Possitive_binary back to decimal: 3 Negative_binary back to decimal: 253
As we can see the negative -3 became 253.
So is there a way to convert the negative decimals to binary and back to decimal?
Answer for future reference:#!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub dec2bin { my $bits = shift; my $str = unpack("B8", pack("c", $bits)); return $str; } sub bin2dec { return unpack("c", pack("B8", substr("0" x 8 . shift , -8))); } my $floating2binary = dec2bin(-127); print "Binary from floating: ".$floating2binary."\n"; my $binary2floating = bin2dec($floating2binary); print "Binary from floating: ".$binary2floating."\n"; __END__ Binary from floating: 10000001 Binary from floating: -127
|
|---|