Reputation: 85
I have an array of hex values in node js that has hex values such as this: ['2ea','1b1'...]. The array does not have a fixed amount of values. The amount of values can change each time. I have been trying to come up with a for loop that would add the hex values up. But it isnt working. Please help. The code below is not correct.
for (var i=0; i<checkSumArray.length; i++) {
function CheckSumFinal(c1, c2) {
var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
return hexStr;
}
var n7= CheckSumFinal(checkSumArray[i], checkSumArray[i+1]);
}
Upvotes: 1
Views: 1553
Reputation: 318342
Keep the variables outside the loop, and just add up inside the loop
var checkSumArray = ['2ea','1b1', 'fff', '4a1', '1e1'],
hexStr = 0;
for (var i=0; i<checkSumArray.length; i++) {
hexStr += parseInt(checkSumArray[i], 16);
}
hexStr = hexStr.toString(16);
document.body.innerHTML = '<pre>' + hexStr + '</pre>'
Upvotes: 2
Reputation: 745
For calculating sums over an array reduce
would be perfect. The idea is to calculate the sum first and just convert the final answer to base16 string.
checkSumArray.reduce(function(p, c){
return p + parseInt(c, 16);
}, 0).toString(16);
Upvotes: 3