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. 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.
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)?
I have tried converting float
to char*
like this:
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
. 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.