Skip to content

Instantly share code, notes, and snippets.

@lovubuntu
Created November 23, 2019 13:07
Show Gist options
  • Save lovubuntu/73f46381c3e9a2fab99e8c8a10afb109 to your computer and use it in GitHub Desktop.
Save lovubuntu/73f46381c3e9a2fab99e8c8a10afb109 to your computer and use it in GitHub Desktop.
two's complement in JS
// 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