Reputation: 152216
I hava a following bit string:
var input = '11100001';
I want to check if eight bit is present, so I have tried with:
input & '10000000'
but it gives me 8918528
. How should I test it ?
Upvotes: 1
Views: 756
Reputation: 22280
Adding to @pawel's excellent answer, let me explain why you get 8918528
:
As soon as JavaScript sees this:
'11100001' & '10000000'
it will try to cast the two strings to integers; Integers in base 10 precisely. So we get:
11100001 (base10) & 10000000 (base10)
which is,
101010010101111101100001 (base2) & 100110001001011010000000 (base2)
Applying bit-wise AND,
101010010101111101100001 &
100110001001011010000000
------------------------
100010000001011000000000 (base2)
Which is,
8918528 (base10)
Upvotes: 4
Reputation: 36965
You're trying to do a bitwise AND on two strings, which implicitly converts them to integers assuming base 10. You should parse them to integers explicitly supplying the base:
parseInt(input,2) & parseInt('10000000',2)
// 128
Edit:
to check if n
-th bit is set you could just shift to right by n-1
bits and check if it's 1
parseInt(input,2) >> 7 & 1 === 1
Upvotes: 7