Created
October 29, 2019 19:33
-
-
Save blaskovicz/1b5a34eeddde8f30f17d87247e7a68ea to your computer and use it in GitHub Desktop.
addHex, nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addHex(left /*: string*/, right /*: string*/) /*: string*/ { | |
if (left.length < right.length) { | |
[left, right] = [right, left]; | |
} | |
// left is "longer" | |
// left = a b c | |
// right = d | |
// --> add c + d, | |
// --> carry 1 to b + <nothing> | |
// --> ... etc | |
let carry = 0; | |
const zero = '0'; | |
const max = 0xf; | |
for (let i = 0, leftLen = left.length, rightLen = right.length; i < leftLen; i++) { | |
const leftI = leftLen - i - 1; | |
const rightI = rightLen - i - 1; | |
const atLeft = parseInt(left[leftI], 16); | |
const atRight = parseInt(rightI < 0 ? zero : right[rightLen - i - 1], 16); | |
let newLeft = atLeft + atRight + carry; | |
if (newLeft > max) { | |
carry = 1; | |
newLeft -= max; | |
} else { | |
carry = 0; | |
} | |
left = left.substr(0, leftI) + newLeft.toString(16) + left.substr(leftI + 1); | |
} | |
if (carry) { | |
left = '1' + left; | |
} | |
return left; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment