[英]Conversion from float to char[32] (or vice-versa) in C
我有兩個變量:一個名為diff
的float
值,其值類似於894077435904.000000
(並不總是只有十進制部分為零)和一個char[32]
,它是double-sha256計算的結果。 我需要在它們之間進行比較( if(hash < diff) { //do someting }
),但是為此,我需要將其中一種轉換為另一種類型。
有沒有辦法做到這一點? 例如,將float
轉換為char*
(並使用strcmp
進行比較)或將char*
為float
(並使用上述方法-如果有可能,請考慮char*
為256位或32字節長) ?
我試過像這樣將float
轉換為char*
:
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
。 如何驗證該值是否正確? 使用此轉換器,我得到不同的結果。
在此對其進行詳細說明。
memcmp
將其與原始二進制文件中的哈希進行比較。 示例代碼:
#include <stdio.h>
#include <string.h>
char* tohex="0123456789ABCDEF";
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.