2014-03-29 210 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個字節大小的浮點數據類型。