JonHodgson
New User
Mar 25, 2007, 9:32 PM
Post #1 of 4
(3422 views)

Problem converting 64bit binary (qword) to float (Win32)

Can't Post


I need to convert 64bit (8byte) binary data to doubleprecision floating point. I need this: 0100000001001001000000000000000000000000000000000000000000000000 To convert to floating point 50.00 I tried unpack, but it's builtin float is only 32bit. See the test code below where unpack gives the same results for all 64 bits as when only using the first 32 bits.
my $binary64 = '0100000001001001000000000000000000000000000000000000000000000000'; # Hex: 4049000000000000 Decimal: 50 my $unpacked64 = unpack('d',$binary64); print "64 Bits: $binary64\n"; print "Unpacked with 'd': $unpacked64\n\n"; # Compare to same string as above, but truncated to 32bits my $binary32 = substr($binary64,0,32); # Hex: 40490000 my $unpacked32 = unpack('d',$binary32); print "32 Bits: $binary32\n"; print "Unpacked with 'd': $unpacked32\n"; OUTPUT:
Bits: 0100000001001001000000000000000000000000000000000000000000000000 Unpacked with 'd': 1.39804328609537e076 Bits: 01000000010010010000000000000000 Unpacked with 'd': 1.39804328609537e076 (The 64bit number should be 50 in decimal) I'm using Bit::Vector for my 64bit long conversions, but that doesn't support floats. While Math::BigInt supports binary input (just preface the binary string with '0b'), that doesn't work for Math::BigFloat
my $binary64 = '0100000001001001000000000000000000000000000000000000000000000000'; use Math::BigInt; my $bigInt = Math::BigInt>new('0b'.$binary64); print "64bits as INT: $bigInt\n"; use Math::BigFloat; my $bigFloat = Math::BigFloat>new('0b'.$binary64); print "64bits as Float: $bigFloat\n"; OUTPUT:
64bits as INT: 4632233691727265792 Can't use an undefined value as a SCALAR reference at c:/Perl/lib/Math/BigFloat.pm line 177. Does anyone have any suggestions? I just hit a brick wall on my project.
