[英]Conversion from float to char[32] (or vice-versa) in C
I have two variables: a float
named diff
with a value like 894077435904.000000
(not always only with zero in the decimal part) and a char[32]
which is the result of a double-sha256 calculation. 我有两个变量:一个名为
diff
的float
值,其值类似于894077435904.000000
(并不总是只有十进制部分为零)和一个char[32]
,它是double-sha256计算的结果。 I need to do a comparison between them ( if(hash < diff) { //do someting }
), but for this I need to convert one to the type of the other. 我需要在它们之间进行比较(
if(hash < diff) { //do someting }
),但是为此,我需要将其中一种转换为另一种类型。
Is there a way to accomplish this? 有没有办法做到这一点? For example, converting the
float
to a char*
(and using strcmp
to do the comparison) or the char*
to float
(and using the above approach - if it's even possible, considering the char*
is 256 bits, or 32 bytes long)? 例如,将
float
转换为char*
(并使用strcmp
进行比较)或将char*
为float
(并使用上述方法-如果有可能,请考虑char*
为256位或32字节长) ?
I have tried converting float
to char*
like this: 我试过像这样将
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);
When I have diff=894077435904.000000
I get hex_str=d02b2b00
. 当我有
diff=894077435904.000000
我得到hex_str=d02b2b00
。 How can I verify if this value is correct? 如何验证该值是否正确? Using this converter I obtain different results.
使用此转换器,我得到不同的结果。
It is explained in great detail here . 在此对其进行详细说明。
memcmp
to compare it to the hash in raw binary. memcmp
将其与原始二进制文件中的哈希进行比较。 Example code: 示例代码:
#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);
}
Output: 输出:
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.