Reputation: 312
Why is in JavaScript:
console.log('1000' | '1010'); // 1018
not '1010'?
and
console.log('1000' & '1010'); // 992
not '1000'?
What ist the right way for bitwise calculation in JavaScript?
Upvotes: 2
Views: 710
Reputation: 892
input numbers need to be defined in binary. after operation you need to convert the result to binary again since bitwise operation produces decimal number. following code will produce your desired output.
console.log(('0b1000' | '0b1010').toString(2));
console.log(('0b1000' & '0b1010').toString(2));
Upvotes: 3
Reputation: 658
it's using the binary equivalent of the decimal numbers you put in. You are actually getting
0000001111101000 | 0000001111110010
0000001111101000 & 0000001111110010
which are equivalent to 1018 and 992 in decimal
Upvotes: 4
Reputation: 5742
You have to define the input as binary number :
console.log(0b1000 | 0b1010);
> 10
Then you can convert back the decimal number to binary notation:
Number(10).toString(2);
> "1010"
Upvotes: 4