gpt4 book ai didi

c++ - 将哈希值存储到 int

转载 作者:行者123 更新时间:2023-11-28 05:40:52 25 4
gpt4 key购买 nike

我已经实现了一个 sha1 散列函数。散列函数正确地打印出散列值,但没有将散列值正确地存储到 int 变量中。请帮助我,我已经尝试了一整天,但我无法纠正错误。感谢您的帮助。

这是函数

void hashSentence1(string Message1)

{



//sha1 hash is 20 bytes

unsigned char hash[20];

unsigned int ihexvalue;
stringstream str;


// compute the sha1 of the input, and store it our hash array

SHA1((unsigned char*)Message1.c_str(), Message1.size(), hash);





// convert the hash array to hexadecimal values and print out

cout << "Hash of first message was: ";

for(int i = 0; i < 20; ++i)

{

cout << hex << (int)hash[i];
str << hex << (int)hash[i];
str >> ihexvalue;

}

cout << endl << "ihexvalue " << ihexvalue;


cout << endl << endl;



}

这是输出,int 变量应该与 sha1 具有相同的值

Message to be hash edbfbeabc123

sha1 - > df7dd80ba924cdef4421d4d73b26323793e24df

ihexvalue -> df

最佳答案

您的循环会在每次循环迭代时设置和重置 ihexvalue 的值。因此,在循环之后,ihexvalue 只包含 hash[19] 的最终值。您可以从输出中看到这一点,它与哈希序列的末尾相匹配。*

为了解决这个问题,您需要仔细考虑您的意图。您可以使用移位和 ORing 将更多数字打包成一个整数。但是,一个整数不足以容纳哈希中的所有信息。

*如评论中所述,您的测试示例在散列的开头和结尾处具有相同的值。仔细观察,所有循环迭代都使用相同的 stringstream str。在这种情况下,如果您发现 ihexvalue 一直从 str 读取相同的值,那是因为 str 正在累积写入它的内容,而 ihexvalue 每次仍然只是从 str 读取第一个值。您会看到这在调试检查中不断获得相同的值。

无论哪种方式,基本问题都是相同的。每次循环迭代都设置或重置 ihexvalue 的值。

如果您为每次循环迭代使用新的(或重置的)字符串流,则意味着每次读取不同的值。然而,仅此并不能解决 ihexvalue 的值每次都被重置的根本问题。

如果您更改为整数(或短整数或无符号字符) vector 之类的东西,您可以使用 .push_back(ihexvalue) 在每次循环迭代的末尾添加新值,并且它可以增长到只要需要。

就是说,我还建议您考虑一下为什么要经历将其转换为文本以写入字符串流,然后从字符串流中读取文本以将其转换回数字表示的方式。由于您在开始使用的 unsigned char 数组中已经有了数值,那么通过进出 stringstream 的昂贵过程,您是否真的有所收获?我不知道上下文,但您可能会发现绕山很远只是为了回到您开始时使用的整数值。

关于c++ - 将哈希值存储到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37121812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com