Question

I am trying to get Double-precision floating-point format double value from binary reader.

I am using std::ifstream in C++.

I have C# code here.

But I have no idea about what BitConverter does.

So, someone give me a hand to convert to C++ or C code.

byte[] bytes = ReadBytes(8);   -> ReadBytes is from BinaryReader class.
byte[] reverse = new byte[8];
//Grab the bytes in reverse order 
for(int i = 7, j = 0 ; i >= 0 ; i--, j++)
{
    reverse[j] = bytes[i];
}
double value = BitConverter.ToDouble(reverse, 0);

EDIT

According to BLUEPIXY, I could create c++ code for that.

char bytes[8];
file.read(bytes, 8);
char reverse[8];
for (int i = 7, j = 0; i >= 0; i--, j++)
{
    reverse[j] = bytes[i];
}
double value = *(double*)reverse;

Thanks to BLUEPIXY.

Was it helpful?

Solution 2

#include <stdio.h>
#include <stdlib.h>

typedef unsigned char byte;

byte *ReadBytes(const char *filename, size_t size){
    FILE *fp = fopen(filename, "rb");
    byte *buff = malloc(size);
    byte *p = buff;

    while(size--)
        *p++ = fgetc(fp);
    fclose(fp);

    return buff;
}

int main(){
    byte *bytes = ReadBytes("data.txt", 8);
    byte *reverse = malloc(8);
    for(int i=7, j=0; i >= 0; --i, ++j)
        reverse[j] = bytes[i];

    double value = *(double*)reverse;
    printf("%f\n", value);
    free(bytes);free(reverse);
    return 0;
}

OTHER TIPS

What the code does is something similar to the read part of this sample;

#include <fstream>
#include <iostream>

int main() {

  // Write the binary representation of a double to file.
  double a = 47.11;
  std::ofstream stream("olle.bin");
  stream.write((const char*)&a, sizeof(a));
  stream.close();

  // Read the contents of the file into a new double.    
  double b;
  std::ifstream readstream("olle.bin");
  readstream.read((char*)&b, sizeof(b));
  readstream.close();

  std::cout << b << std::endl;    // Prints 47.11
}

In other words, it just reads raw bytes from the stream into a double. Sadly, a double in C is not in any way guaranteed to be a fixed size so you're not guaranteed to have a floating point datatype that is 8 bytes of size that you can use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top