简体   繁体   English

在 Javascript 和 C++ 中计算 MD5 哈希的不同结果

[英]Different outcome calculating MD5 hash in Javascript and C++

I am trying to calculate an MD5 hash for a certain value in Javascript and in C++ but the different programming languages are giving different outputs at times.我试图在 Javascript 和 C++ 中计算某个值的 MD5 哈希,但不同的编程语言有时会给出不同的输出。 As it does not happen constantly I am guessing it has something to do with rounding errors.由于它不会经常发生,我猜它与舍入误差有关。

In Javascript I am calculating the value as follows:在 Javascript 中,我计算的值如下:

let calculatedTotal = 0;
blocks.forEach((block) => {
   calculatedTotal += Math.floor(block.standard_deviation * 1000);
});

In C++ using rapidJson I am doing:在 C++ 中使用 RapidJson 我正在做:

for (rapidjson::Value::ConstValueIterator j = blocks.Begin(); j != blocks.End(); ++j) {
    float val = (*j)["standard_deviation"].GetFloat();
    sumToCalculteHashOver += int(std::floor(val * 1000));
}

As shown in C++ I am using a float.如 C++ 所示,我使用的是浮点数。

Does anyone know what could be the cause of this?有谁知道这可能是什么原因?

I managed to solve this thanks to @Caramiriel.感谢@Caramiriel,我设法解决了这个问题。

The issue has, as I kinda expected, to do with the precision of floating point numbers in C++.正如我所料,这个问题与 C++ 中浮点数的精度有关。

Using an integer value in my calculations worked.在我的计算中使用整数值有效。 For me that meant I needed to make these changes.对我来说,这意味着我需要做出这些改变。

Javascript: Javascript:

let calculatedTotal = 0;
blocks.forEach((block) => {
   calculatedTotal += Math.floor(block.standard_deviation) * 1000;
});

C++: C++:

for (rapidjson::Value::ConstValueIterator j = blocks.Begin(); j != blocks.End(); ++j) {
    int val = int(std::floor((*j)["standard_deviation"].GetFloat()));
    sumToCalculteHashOver += int(std::floor(val * 1000));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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