2017-08-29 126 views
0

我有兩個變量:a float名爲diff與值等894077435904.000000(並不總是僅與小數部分零)和char[32]這是雙重sha256計算的結果。我需要對它們進行比較(if(hash < diff) { //do someting }),但爲此我需要將其中一個轉換爲另一個的類型。轉換到char [32](或反之亦然)用C

有沒有辦法做到這一點?例如,將float轉換爲char*(並使用strcmp進行比較)或char*至至float(並且使用上述方法 - 如果甚至可能,考慮char*是256位或32字節長)?

我試圖轉換floatchar*這樣的:

char hex_str[2*sizeof(diff)+1]; 
snprintf(hex_str, sizeof(hex_str), "%0*lx", (int)(2*sizeof diff), (long unsigned int)diff); 
printf("%s\n", hex_str); 

當我有diff=894077435904.000000我得到hex_str=d02b2b00。我如何驗證這個值是否正確?使用this converter我獲得了不同的結果。

+0

你需要做數學題的難度轉換到目標,然後你需要爲目標比較散列結果(可能用'memcmp')。有關如何將難度轉換爲目標的更多信息,請參見[這裏](https://en.bitcoin.it/wiki/Difficulty)。 –

+0

我已經做了這個數學(我從json-rpc接口讀取'bits',轉換爲'unsigned int'並傳遞給你發佈的鏈接中列出的函數)。現在我只需要比較難度和散列,我猜。 –

+0

好的。爲此,使用'memcmp'。如果散列值小於目標值,則獲勝。 –

回答

3

這是詳細解釋here

  1. 創建32個無符號字節的數組,將其所有值設置爲零。
  2. 從難度提取頂部字節和減去從32
  3. 從複製的難度爲陣列的底部的三個字節,開始在步驟2.
  4. 此計算字節到所述陣列的所述數數組現在包含原始二進制的難度。使用memcmp將其與原始二進制文件中的哈希進行比較。

示例代碼:

#include <stdio.h> 
#include <string.h> 

char* tohex="ABCDEF"; 

void computeDifficulty(unsigned char* buf, unsigned j) 
{ 
    memset(buf, 0, 32); 
    int offset = 32 - (j >> 24); 
    buf[offset] = (j >> 16) & 0xffu; 
    buf[offset + 1] = (j >> 8) & 0xffu; 
    buf[offset + 2] = j & 0xffu; 
} 

void showDifficulty(unsigned j) 
{ 
    unsigned char buf[32]; 
    computeDifficulty(buf, j); 
    printf("%x -> ", j); 
    for (int i = 0; i < 32; ++i) 
     printf("%c%c ", tohex[buf[i] >> 4], tohex[buf[i] & 0xf]); 
    printf("\n"); 
} 

int main() 
{ 
    showDifficulty(0x1b0404cbu); 
} 

輸出:

1b0404cb -> 00 00 00 00 00 04 04 CB 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
相關問題