Tuesday, March 10, 2009

Perl: Byte string to Double conversion

Share at Facebook

I'm going to provide an example that will help you convert any 8 byte binary data into double value. This will actually help you to analyze the packet of network transfer if you need any time. Here is the example code. You can modify the code easily.

print bytesToDouble('407E000000000000');

## Take 8 byte string and return corresponding double value
sub bytesToDouble{
my $byte_str = shift;
my @bytes = ();

## make hex byte, then convert into integer
for( my $i = 0; $i < length($byte_str) ; $i += 2){
$bytes[$i/2] = hex('0x' . substr($byte_str, $i, 2) );

$byte_str = pack('C8', reverse(@bytes));
my $double_value = unpack("d", $byte_str);
$double_value = sprintf("%0.3f", $double_value);
return $double_value;

Inside the above example, I have used pack/unpack to handle the conversion between byte and double. Also I have used hex() function to convert hexadecimal formatted string into integer value, and substr() function to extract each 2 byte from provided byte string.

Once again Thanks for reading the posting. Share your thoughts if you interested.

1 comment:

Anonymous said...