简体   繁体   English

在C中从float转换为char [32](反之亦然)

[英]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. 我有两个变量:一个名为difffloat值,其值类似于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 . 此对其进行详细说明。

  1. Create an array of 32 unsigned bytes, set all its values to zero. 创建一个由32个无符号字节组成的数组,将其所有值设置为零。
  2. Extract the top byte from the difficulty and subtract that from 32. 从难度中提取最高字节,然后从32中减去。
  3. Copy the bottom three bytes from the difficulty into the array, starting the number of bytes into the array that you computed in step 2. 将难度中的后三个字节复制到数组中,开始将字节数添加到您在步骤2中计算出的数组中。
  4. This array now contains the difficulty in raw binary. 现在,此数组包含原始二进制文件中的困难。 Use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM