Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert double value to binary value

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

like image 785
raj Avatar asked Feb 09 '10 07:02

raj


3 Answers

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.

like image 90
Jon Skeet Avatar answered Nov 17 '22 22:11

Jon Skeet


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.

like image 21
unwind Avatar answered Nov 17 '22 22:11

unwind


A decade late but hopefully this will help someone:

// Converts a double value to a string in base 2 for display.
// Example: 123.5 --> "0:10000000101:1110111000000000000000000000000000000000000000000000"
// Created by Ryan S. White in 2020, Released under the MIT license.
string DoubleToBinaryString(double val)
{
    long v = BitConverter.DoubleToInt64Bits(val);
    string binary = Convert.ToString(v, 2);
    return binary.PadLeft(64, '0').Insert(12, ":").Insert(1, ":");
}
like image 1
SunsetQuest Avatar answered Nov 17 '22 23:11

SunsetQuest