Created
November 23, 2019 13:07
-
-
Save lovubuntu/73f46381c3e9a2fab99e8c8a10afb109 to your computer and use it in GitHub Desktop.
two's complement in JS
This file contains hidden or 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
// https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html | |
// https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/ | |
const twosComplement = (digits) => { | |
let twosComplementValue = ''; | |
const lastIndexOfOne = digits.lastIndexOf('1'); | |
if(lastIndexOfOne === -1) { | |
return '1' + digits; | |
} | |
for(let i=0; i < lastIndexOfOne; i++) { | |
twosComplementValue += flipBit(digits[i]); | |
} | |
twosComplementValue += digits.substring(lastIndexOfOne); | |
return twosComplementValue; | |
} | |
const flipBit = (bit) => bit === '1' ? '0' : '1'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment