Search code examples
javascriptbitwise-operators

How does '&' work in relation to odd and even? In JS


I was given the task to figure out how to determine odd and even. I could not use %. I used & because I found it out on the internet but I couldn't find a decent for the way it works.

N/A

My sample I created was

`
    if ((22 & 1) === 0) { 
        return true;
    } else{
        return false;
    }`

Returns true


Solution

  • In binary notation the right-most bit is the ones place:

    0 = 0000
    1 = 0001
    2 = 0010
    3 = 0011
    4 = 0100
    5 = 0101
    6 = 0110
    ...etc
    

    So as you can see every odd number ends in 1 and every even ends in 0.

    When you use & you are making a bit-wise and calculation. When you do X & 1, are you comparing each bit of X against 1 or in binary: 00001 (you can keep extending the zeros to the left) and testing wether both bits are 1.

    So for example 22 is 10110 in binary 22 & 1 looks each bit and test if both are true:

    1 0 1 1 0
    0 0 0 0 1 < no bits are 1 in both number
    ---------
    0 0 0 0 0 < all zeros == 0  so 22 is even
    

    23 is 10111:

    1 0 1 1 1
    0 0 0 0 1  the last bit is one in both numbers
    ---------
    0 0 0 0 1 < 1 so 23 is odd
    

    Since the last bit is always 1 in odd numbers x & 1 will always be one for odd numbers and zero for evens.