2011-12-23 17 views
1

我有一個雙數字,我想用IEEE 754 64位二進制字符串表示它。 目前我使用的是這樣的代碼:在C++中將雙數轉換爲(IEEE 754)64位二進制字符串表示形式

double noToConvert; 
unsigned long* valueRef = reinterpret_cast<unsigned long*>(&noToConvert); 

bitset<64> lessSignificative(*valueRef); 
bitset<64> mostSignificative(*(++valueRef)); 

mostSignificative <<= 32; 
mostSignificative |= lessSignificative; 

RowVectorXd binArray = RowVectorXd::Zero(mostSignificative.size()); 
for(unsigned int i = 0; i <mostSignificative.size();i++) 
{ 
    (mostSignificative[i] == 0) ? (binArray(i) = 0) : (binArray(i) = 1); 
} 

上面的代碼只是正常工作沒有任何問題。但是,如果您看到,我正在使用reinterpret_cast並使用無符號long。所以,這段代碼非常依賴於編譯器。任何人都可以告訴我如何編寫一個獨立於平臺且不使用任何庫的代碼。我很好,如果我們使用標準庫甚至是bitset,但我不想使用任何機器或編譯器相關的代碼。

在此先感謝。

+1

假設IEEE 754已經與機器相關。 – Mysticial 2011-12-23 22:29:20

+0

好的,有沒有辦法做到這一點..? – jero2rome 2011-12-23 22:37:28

+0

C99爲x86_64計算機提供了長達80位的擴展精度。但它與x86電腦的雙倍相同。 – Geoffroy 2011-12-23 22:40:54

回答

2

爲什麼不使用聯合?

bitset<64> binarize(unsigned long* input){ 
    union binarizeUnion 
    { 
     unsigned long* intVal; 
     bitset<64> bits; 
    } binTransfer; 
    binTransfer.intVal=input; 
    return (binTransfer.bits); 
} 
0

得到這個最簡單的方法是將memcpy的雙入的char數組:

char double_as_char[sizeof(double)]; 
memcpy(double_as_char, &noToConvert, sizeof(double_as_char)); 

,然後從double_as_char提取比特。 C和C++將該標準定義爲合法。現在

,如果你想實際提取double的各個組成部分,可以使用以下命令:

sign= noToConvert<=-0.0f; 
int exponent; 
double normalized_mantissa= frexp(noToConvert, &exponent); 
unsigned long long mantissa= normalized_mantissa * (1ull << 53); 

因爲由frexp返回的值是[0.5, 1),你需要轉移它一個額外的位將尾數中的所有位作爲整數。然後,您只需將其映射到您想要的二進制表示形式,但您必須調整指數以包含隱式偏見。

3

如果你願意承擔double是IEEE-754雙類型:

#include <cstdint> 
#include <cstring> 

uint64_t getRepresentation(const double number) { 
    uint64_t representation; 
    memcpy(&representation, &number, sizeof representation); 
} 

如果你甚至不希望做這樣的假設:

#include <cstring> 

char *getRepresentation(const double number) { 
    char *representation = new char[sizeof number]; 
    memcpy(representation, &number, sizeof number); 
    return representation; 
} 
+0

我想將結果存儲在二進制字符串中。像字符串s =「0011111111101111111101111100111011011001000101101000011100101011」,但是你建議我返回一些像ffffff @¬%¿Woò – jero2rome 2011-12-23 23:20:11

+0

@Jero:我建議給你的內存中的實際表示。您可以從中讀取位模式,而不會調用未定義的行爲。 – 2011-12-24 00:46:19

1

功能print_raw_double_binary ()在我的文章Displaying the Raw Fields of a Floating-Point Number應該接近你想要的。你可能想用union來替換double的int類型爲int,因爲前者違反了「嚴格別名」(儘管使用union來訪問不同於存儲內容的東西在技術上是非法的)。

相關問題