Why, after 11100, pops up 420, not 00100, but the final value (11000) still matches the original one?

var sir = 11000; alert(sir); var meg = 11100; alert(meg); var tun = sir ^ meg; alert(tun); alert(tun ^ meg); 

  • 3
    And what is wrong? You took 2 decimal numbers. Made XOR and got the right result. Binary recording of a number in js is done in another way, as in many other programming languages, through 0b - ArchDemon
  • But what should be the mistake or what confuses you? - michael_best
  • And how can you specify the belonging of a number to the binary system? I tried to put 0b before the numbers, but there was a transfer to the decimal system. - Artyom Zhdanov

1 answer 1

You write 2 numbers in decimal notation. The ^ (XOR) operation is performed on the bits (!) That represent these 2 numbers.

Those.


11000 10 = 10101011111000 2

11100 10 = 10101101011100 2

Applying to them the operation ^ we get the following:

  00000110100100 2 = 420 10 


"But the final value (11000) still matches the original." - this is one of the properties of the XOR operation: (a XOR b) XOR b = a
This is the hidden subtleties of programming so to speak. At one time, he himself had long caught up with what was happening and how.

  • Is it possible to somehow indicate to which system of calculus the recorded number belongs (in my example to a two-digit one)? - Artem Zhdanov
  • Yes, there is a way - any number represented in a number system other than decimal is written as a string. The toString() method is what you need. Number(sir.toString(2)); - will give a binary representation of the number in the sir variable. But the XOR over this representation will not work anyway :) The line above will give a decimal number and the XOR will work with the bits of this decimal number. As a result, there will be a game - Dmitry
  • To apply XOR to you, I think, the following will suit (parseInt(sir, 2) ^ parseInt(meg, 2)).toString(2) - Dmitry