4

can anyone show how to correctly convert binary represented data into double value in C. for example, i have 8 unsigned char values to be converted to double value (let's name it buffer). so buffer[0]'s 0's bit is LSB, and buffer[7]'s 7's bit is MSB. thanks a lot in advance!

sdfg
  • 393
  • 2
  • 5
  • 9

2 Answers2

4

IF the following are ALL true:

  1. Your machine is little-endian.
  2. On your machine, sizeof(double) == 8
  3. Your machine's idea of a "byte" is the same as that of the machine which saved the data (not all machines use octets/8-bit bytes).
  4. Your machine's floating point format matches that of the machine the data was generated/saved on.

You can simply read the 8 bytes into an array, and do a cast (assumes 'fd' is the open file descriptor):

char bytes[8];
fread(&bytes, 8, 1, fd);
double d = *((double*)bytes);

More generally, however, I'd suggest not saving binary data like that. Yes, it used to be common, and a lot of people still do it, but with modern hardware it's really unnecessary and leads to situations like this, where you can only easily deserialize it if your platform exactly matches the platform on which it was written to disk. Pick a portable format -- human-readable UTF-8 based, if you can -- and use that.

Nicholas Knight
  • 15,774
  • 5
  • 45
  • 57
3

Just cast it, I think

char buf[8];
double x;
...
x = *((double*) buf);
Tom Sirgedas
  • 3,208
  • 20
  • 17
  • 2
    This technique assumes much—same architecture, format, endianness, proper object size—which are okay if the data came from the same machine. – wallyk Aug 10 '10 at 19:35