开发者

Bit-tweaking in Javascript

开发者 https://www.devze.com 2023-02-16 23:26 出处:网络
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 acc

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. R开发者_如何转开发emember no costly functions allowed.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消