2014-03-29 205 views
-3

我想从二进制阅读器中获得双精度浮点格式double值。如何将C#代码转换为C++?

我在C++中使用std :: ifstream。

我在这里有C#代码。

但我不知道什么是BitConverter。

所以,有人给我一只手来转换为C++或C代码。

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); 

编辑

据BLUEPIXY,我可以创建为C++代码。

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; 

感谢BLUEPIXY。

+0

'BitConverter.ToDouble'返回从字节数组中指定位置的八个字节转换而来的双精度浮点数。 – inixsoftware

+0

这个消息的题目很差。编辑它来询问你所遇到的特定问题(并且包括C#示例代码):它不是将C#转换为C++,而是将原始字节转换为“double”。 – Yakk

回答

1
#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; 
} 
+1

上面的C代码。如果免费商店出现故障,它会泄漏并执行UB。 – Yakk

+0

加'free()'。并检查省略。 – BLUEPIXY

+0

从我+1,但其他人不同意。 :) – Yakk

3

代码的功能与本示例的读取部分相似;

#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 
} 

换句话说,它只是从流中读取原始字节为double。遗憾的是,C中的双精度不会以任何方式保证为固定大小,所以您不能保证具有可以使用的8个字节大小的浮点数据类型。