英文:
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));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论