0

Just curious. I did a program in C, with quite an amount of bitwise operations for a variable which defines access controls for a page. I wanna be able to do the same in Javascript only. How can i accomplish this ordeal?

Any help in bit-tweaking in Javascript will help. Remember no costly functions allowed.

5
  • May I recommend you don't write C in JavaScript. Try to use JavaScript like a functional dynamic language instead. Commented Mar 16, 2011 at 13:10
  • I guess i wasn't clear. C coding was used for the server side development. Javascript for the client side. I just wanted to avoid overloading the server. Hence my question. Commented Mar 16, 2011 at 13:33
  • I meant do write JavaScript code in a C-style. It can be easy to write procedural style code in javascript due to the syntax similarities but it just becomes a mess. There really shouldn't be much reason to use bit manipulation in JavaScript apart from classics such as hashing functions. Commented Mar 16, 2011 at 16:08
  • Clearly I meant don't write JavaScript code in C-style. Commented Mar 16, 2011 at 16:21
  • Ahh, Alright. I'll try my best to avoid it. Thanks for the insight! Commented Mar 16, 2011 at 16:36

2 Answers 2

1

JavaScript has the usual assortment of bitwise operators, |, &, ~, etc.; details in the specification.

The following sections will be particularly useful:

  • Section 11.4.8: Bitwise NOT (~)
  • Section 11.7: Bitwise Shift Operators (<< and >>)
  • Section 11.10: Binary Bitwise Operators (| and &)

Note that JavaScript's numbers are all floating point (see Section 8.5, The Number Type, in the specification), but the bitwise operations are defined in terms of integers. So for instance, the definition of the bitwise NOT operator:

11.4.8 Bitwise NOT Operator ( ~ )
The production UnaryExpression : ~ UnaryExpression is evaluated as follows:
1. Let expr be the result of evaluating UnaryExpression.
2. Let oldValue be ToInt32(GetValue(expr)).
3. Return the result of applying bitwise complement to oldValue. The result is a signed 32-bit integer.

Any decent implementation will be able to handle these efficiently, avoiding unnecessary conversions from Number to internal integer and back.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Quite comprehensive.
And for even more details see bateru.com/news/2011/03/…
1

JavaScript has bitwise operators like other languages. Bitwise operators are, by definition, efficient. You should be able to replicate all the bitwise operations performed in your C program in JS as well.

http://www.eecs.umich.edu/~bartlett/jsops.html

Comments

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.