-1

Am trying to XOR Two Strings. It's returning value with exponential notation, but in my case i need to pad the unmatched string with 0's.

x1 = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
x2 = "00000000000000000000000000000000011000000000000000000000000000000000000000000000000000000";
xor1 = parseInt(x1, 2);
xor2 = parseInt(x2, 2);
console.log(xor1, xor2);
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
  • 1
    Those numbers are too big for JavaScript to handle precisely. Consider using string functions instead. – Niet the Dark Absol Nov 27 '16 at 14:04
  • Do it one character at a time and concatenate the result. Just write you own XOR for characters. Look at http://stackoverflow.com/questions/20566421/xor-of-two-hex-strings-in-javascript for some ideas. – PM 77-1 Nov 27 '16 at 14:07
  • what does this have to do with angularjs? Don't use a framework tag for a language question just because you use the framework in other parts of your app.... – Claies Nov 27 '16 at 14:53

1 Answers1

2

In your code, you are parsing the string to binary numbers. parseInt("0001100", 2) is 0b001100, or 12 in decimal. The numbers you're attempting to parse are way larger than MAX_SAFE_INTEGER, but that's kind of irrelevant anyway...

It's not possible to add leading zeroes to a number using xor, since the leading numbers are implicitly there anyway, so it won't change the representation of the number:

(0b0000 ^ 0b100) === 0b100, so toString(2)-ing that will leave you with "100".

You'll need to go through your string character by character and build a string from it.

let x =    "11000000000000000000000000000000000000000000000000000000";
let mask = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

let result = mask.split("").reduceRight(function(partialResult, value, index) {
  if (index < x.length && x.charAt(x.length - index - 1) === "1") {
    return partialResult + "1";
  } else {
    return partialResult + "0";
  }
}, "");

console.log("Result is: " + result);
clinton3141
  • 4,751
  • 3
  • 33
  • 46