代码之家  ›  专栏  ›  技术社区  ›  Jonathan Zea

将格式化的打印值存储在新变量中

  •  -1
  • Jonathan Zea  · 技术社区  · 9 年前

    在加密函数(sha256)中,我有此代码用于打印最终结果:

    void print_hash(unsigned char hash[]) 
       {
           int idx;
           for (idx=0; idx < 32; idx++)
              printf("%02x",hash[idx]);
           printf("\n");
        }
    

    当函数中的哈希输入类似于:

    /A�`�}#.�O0�T����@�}N�?�#=\&@
    

    然后,通过循环,我进入控制台

    182f419060f17d2319132eb94f30b7548d81c0c740977d044ef1edbb9b97233d
    

    我想知道如何将控制台中的最终值存储在变量中。 我读过一些关于sscanf的文章,但你能帮我吗?

    3 回复  |  直到 9 年前
        1
  •  1
  •   ouah    9 年前

    您可以使用 sprintf :

    void print_hash(unsigned char hash[], unsigned char output[])
    {
        int idx;
        for (idx = 0; idx < 32; idx++)
            sprintf(&output[2 * idx], "%02x", hash[idx]);
    }
    

    请确保为中的空终止符保留一个额外的字节 output (即。, char output[2 * 32 + 1] ).

        2
  •  0
  •   Shadowwolf    9 年前

    使用 sprintf ,此函数存储其输出(相当于 printf 写入控制台)。如何在您的案例中使用它的示例:

    char buffer[65]; //Make this buffer large enough for the string and a nul terminator
    for(int idx = 0; idx < 32; ++idx)
    {
        sprintf(&buffer[2*idx], "%02x", hash[idx]); //Write to the correct position in the buffer
    }
    

    终止的nul字符由自动附加 把格式数据写成串 .

        3
  •  0
  •   Iharob Al Asimi    9 年前

    您也可以避免使用 sprintf() 做一个更有效的函数

    void
    hash2digest(char *result, const char *const hash, size_t length)
    {
        const char *characters = "0123456789abcdef";
        for (size_t i = 0 ; i < length ; ++i)
        {
            result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
            result[2 * i + 1] = characters[hash[i] & 0x0F];
        }
        result[2 * length] = '\0';    
    }
    

    请注意,您可以像这样从任何地方调用它(假设 hash 已声明和定义)

    char digest[65];
    hash2digest(digest, hash, 32);
    

    这反过来又可用于 SHA1 例如,像这样

    char digest[41];
    hash2digest(digest, hash, 20);
    

    使用动态内存分配

    char *
    hash2digest(const char *const hash, size_t length)
    {
        const char *characters = "0123456789abcdef";
        char *result;
        result = malloc(2 * length + 1);
        if (result == NULL)
            return NULL;
        for (size_t i = 0 ; i < length ; ++i)
        {
            result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
            result[2 * i + 1] = characters[hash[i] & 0x0F];
        }
        result[2 * length] = '\0';
    
        return result;
    }