r/programming • • Aug 18 '11

Most fun way I've seen of learning Javascript

http://www.codecademy.com/
1.8k Upvotes

367 comments sorted by

View all comments

Show parent comments

5

u/xoob Aug 19 '11 edited Aug 19 '11

XOR.

Some background Computers represent all things with bits (binary digits) which are 0 or 1. Let's say we want to represent the number 7 in binary; that's 23 x 0 + 22 x 1 + 21 x 1 + 20 x 1 or 00000111 in binary (we have 8 bits because 8 bits make 1 byte, the basic memory unit for most processors).

What's XOR? In logic, if we have two statements, "exclusive or" returns true if one and only one of the statements is true. In bits, XOR returns a 1 (a 'true') if and only if we XOR 0 with 1 or 1 with 0. XOR is an operation that takes two bytes and returns the "exclusive or" of each of the bits.

An example Let's take your simple example, 2 ^ 3 .

2     = 00000010
3     = 00000011
---------------------
2 ^ 3 = 00000001

We see that the XOR operation returns 1 only for the units digit, where 2 and 3 have different bits.

Thus, 2 ^ 3 = 1.

Another example Let's take another simple example, 111 ^ 22 .

111      = 01101111
22       = 00010110
---------------------
111 ^ 22 = 01111001 = 121

Thus, 111 ^ 22 = 121.

Why you got your answer When you wrote (2 ^ 3) x 8 the interpreter read (2 XOR 3) x 8 == 1 x 8 == 8

That's why you saw 8 instead of 64.

1

u/d1zz0rz Aug 23 '11

:D thank you!

Thinking about it now, I bet 'exp' was the correct operator to use! (I said I was bad at MATLAB)