-2
Well, according to the website Imasters they define the utility of the bitwise operator and as:
The operator & ( Bitwise AND ) compares two values using their binary representations, returning a new value. To form this return value, each bit is compared, returning 1( true ) when both bits are equal to 1( true ); otherwise, returns 0( false ).
So far so good, but note this example:
let n1 = 1; // 00110001
let n2 = 2; // 00110010
console.log(n1 & n2);
The above example has the return 0
(false
), that’s because 1
has the binary representation 00110001
and the 2
has binary representation 00110010
, then both are not equal, but in the example below will return 1
(true
), because they both contain the same binary representation:
let n1 = 1; // 00110001
let n2 = 1; // 00110001
console.log(n1 & n2);
But in the example below it will return 0
(false
):
let n1 = 0; // 00110000
let n2 = 0; // 00110000
console.log(n1 & n2);
Because the return is 0
(false
) if both contain the same binary representation?
A hint to see the binary representation of a number:
n1.toString(2)
. If you want with the zeroes on the left, you can don1.toString(2).padStart(8, "0")
– hkotsubo
hkotsubo, but what this command does
padStart(8, "0")
– user173282
Put the zeros in front, completing a maximum of 8 characters.
– hkotsubo
Thank you you are the guy!
– user173282