1

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 ?

2
  • 1
    Why do you use strings? Bitwise operators work on numbers. Commented Aug 7, 2014 at 11:19
  • @Bergi I get it from API. Looks like, parsing to int is a solution then. Commented Aug 7, 2014 at 11:21

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

4

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)

1 Comment

Great work with this detailed explanation, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.