Search code examples
rieee-754hexdump

readBin doesn't produce expected output


I need to convert the IEEE-754 format into a double precision floating point number.

According to https://babbage.cs.qc.cuny.edu/IEEE-754.old/64bit.html the Hex representation 400921fb54442d18 should be roughly pi, 3.1415...

However:

> readBin(as.raw(c(0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18)), 'double')
[1] 3.207376e-192

How do I get pi from 400921fb54442d18 in R?


Solution

  • When reading multibyte numbers, you need to be mindful of "endianness" which determines the order of the bytes. This raw value appears to be in "big" endian format which must not the the default on your system. Try

    readBin(as.raw(c(0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18)), 'double', endian="big")
    # [1] 3.141593
    

    With little endian format, those bytes would just be reversed. So you could also do

    # assuming .Platform$endian returns "little" (system default)
    readBin(rev(as.raw(c(0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18))), 'double')