convert double value to binary value

14,138

Solution 1

Well, you haven't specified a platform or what sort of binary value you're interested in, but in .NET there's BitConverter.DoubleToInt64Bits which lets you get at the IEEE 754 bits making up the value very easily.

In Java there's Double.doubleToLongBits which does the same thing.

Note that if you have a value such as "125252525235558554452221545332224587265" then you've got more information than a double can store accurately in the first place.

Solution 2

In C, you can do it for instance this way, which is a classic use of the union construct:

int i;
union {
 double x;
 unsigned char byte[sizeof (double)];
} converter;

converter.x = 5.5555555555556e18;

for(i = 0; i < sizeof converter.byte; i++)
  printf("%02x", converter.byte[i]);

If you stick this in a main() and run it, it might print something like this:

~/src> gcc -o floatbits floatbits.c
~/src> ./floatbits
ba b5 f6 15 53 46 d3 43

Note though that this, of course, is platform-dependent in its endianness. The above is from a Linux system running on a Sempron CPU, i.e. it's little endian.

Share:
14,138
raj
Author by

raj

Updated on June 18, 2022

Comments

  • raj
    raj almost 2 years

    How can i convert double value to binary value.

    i have some value like this below 125252525235558554452221545332224587265 i want to convert this to binary format..so i am keeping it in double and then trying to convert to binary (1 & 0's).. i am using C#.net

  • paxdiablo
    paxdiablo about 14 years
    You may want to mention that the 8 is for a very specific data type. I don't think IEEE754 64-bit is mandated by the C standard.
  • raj
    raj about 14 years
    i have some value like this below 125252525235558554452221545332224587265 i want to convert this to binary format..so i am keeping it in double and then trying to convert to binary (1 & 0's).. i am using C#.net
  • Rick Regan
    Rick Regan about 14 years
    BTW, that number is 127 bits long so can only be approximated (poorly) with a double.