转换到char [32](或反之亦然)用C
问题描述:
我有两个变量:a float
名为diff
与值等894077435904.000000
(并不总是仅与小数部分零)和char[32]
这是双重sha256计算的结果。我需要对它们进行比较(if(hash < diff) { //do someting }
),但为此我需要将其中一个转换为另一个的类型。转换到char [32](或反之亦然)用C
有没有办法做到这一点?例如,将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
。我如何验证这个值是否正确?使用this converter我获得了不同的结果。
答
这是详细解释here。
- 创建32个无符号字节的数组,将其所有值设置为零。
- 从难度提取顶部字节和减去从32
- 从复制的难度为阵列的底部的三个字节,开始在步骤2.
- 此计算字节到所述阵列的所述数数组现在包含原始二进制的难度。使用
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
你需要做数学题的难度转换到目标,然后你需要为目标比较散列结果(可能用'memcmp')。有关如何将难度转换为目标的更多信息,请参见[这里](https://en.bitcoin.it/wiki/Difficulty)。 –
我已经做了这个数学(我从json-rpc接口读取'bits',转换为'unsigned int'并传递给你发布的链接中列出的函数)。现在我只需要比较难度和散列,我猜。 –
好的。为此,使用'memcmp'。如果散列值小于目标值,则获胜。 –