Vee6
Vee6

Reputation: 1577

javascript bitwise and yielding weird results

In one of my applications in order to simplify logic / heavy db stuff I created a mechanism that relies on the javascript bitwise '&' operator. However this seems to act weird in some occasions.

1 & 0 => 0;  11 & 00 => 0;  111 & 000 => 0; 111 & 100 => 100

everything ok so far.. but when I try to do this:

1100 & 0011 => 8 ;
1100 & 1111 => 1092

I get weird results, instead of 0 or 1100. I found out that this happens due to some 'javascript interpretation in a specific base' stuff, however I wonder if there is a solution to this.

Upvotes: 0

Views: 189

Answers (3)

Himanshu Goel
Himanshu Goel

Reputation: 594

As per your question you are performing bitwise operation between decimal numbers not binary numbers. In javascript binary number is represented by prefixing 0b for eg 2 should be represented as 0b10. Another thing is that javascript returns decimal number as a result of bitwise operation. Similarly hexadecimal number is represented using prefex 0x.

Upvotes: 2

mld
mld

Reputation: 36

Javascript doesn't act weird. You're typing decimal numbers which translate to:

decimal 1100 = binary 0000010001001100
decimal 0011 = binary 0000000000001011

if you & them you will get

0000000000001000

which is 8

the same is with 1100 & 1111

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

When you type 1100 you aren't producing the binary representation of 12, you're writing 1100. When a number is prefixed with a 0, Javascript interprets that number as being an octal number.

In short, make sure you give the correct decimal numbers to get the proper binary representation.

Upvotes: 1

Related Questions