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

huangapple go评论83阅读模式
英文:

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. 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:

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

In C++ using rapidJson I am doing:

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

As shown in C++ I am using a float.

Does anyone know what could be the cause of this?

英文:

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. 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:

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

In C++ using rapidJson I am doing:

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.

Does anyone know what could be the cause of this?

答案1

得分: 0

我成功解决了这个问题,感谢 @Caramiriel。

问题与C++中浮点数的精度有关,正如我有点预期的那样。

在我的计算中使用整数值起作用。对我来说,这意味着我需要进行以下更改。

Javascript:

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

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));
}
英文:

I managed to solve this thanks to @Caramiriel.

The issue has, as I kinda expected, to do with the precision of floating point numbers in C++.

Using an integer value in my calculations worked. For me that meant I needed to make these changes.

Javascript:

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

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));
}

huangapple
  • 本文由 发表于 2020年1月6日 17:43:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定