Thursday, February 19, 2015

DEC2IEEE 32 Bits

agus@agus-Satellite-L840:~/SCRIPT$ perl dec2ieee.pl
input decimal: -12.0986565656
IEEE 32 bits string: 11000001010000011001010000011001
recovered decimal: -12.0986566544




#!/bin/usr/perl
my $data = -12.0986565656;
print "input decimal: $data","\n";
$nolsatu=sprintf ("%b",unpack('L',pack('f',$data)));

if($data > 0)
   {
$nol=0;
$nol.= $nolsatu;
$databin = $nol;
   } else
   {
$databin = $nolsatu;
   }
print "IEEE 32 bits string: $databin","\n";
$decimal=conv_bit_string_2_ieee32float($databin),"\n";
print "recovered decimal: $decimal","\n";

sub bin2dec {
return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

sub conv_bit_string_2_ieee32float {
$bit_string_ieee = shift;
$first_digit_ieee = substr($bit_string_ieee, 0, 1);
if ( $first_digit_ieee eq "0" ) {
$sign_bit_ieee = 1;
} elsif ( $first_digit_ieee eq "1" ) {
$sign_bit_ieee = -1;
}
$bin_exponent_ieee = substr($bit_string_ieee, 1, 8);
$exponent_ieee = bin2dec($bin_exponent_ieee);
$bin_fraction_ieee = substr($bit_string_ieee, 9, 63);
@bit_chars_ieee = unpack("A1" x length($bin_fraction_ieee), $bin_fraction_ieee);
$place_holder_ieee = -1;
$fraction_ieee = 0;
foreach $bit_ieee ( @bit_chars_ieee ) {
$fraction_ieee += $bit_ieee * (2 ** $place_holder_ieee);
$place_holder_ieee += -1;
}
$ieee_float_ieee = ($sign_bit_ieee ** 1) * (1+$fraction_ieee)*(2**($exponent_ieee - 127));
return sprintf("%.10f", $ieee_float_ieee);
}

No comments: