Why bitwise operators?

R

Randell D.

Why would one use bitwise operators? I can program in various languages in
some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
operators before, but never understood why anyone would use them - any real
world examples or ideas? Examples follow (that I am reading in my Core
JavaScript Guide 1.5).

15 & 9 yields 9 (1111 & 1001 = 1001)
15 | 9 yields 15 (1111 | 1001 = 1111)
15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
in addition there are AND,OR,XOR,NOT and left and right shifts which would
only extend this post longer than nescessary...
 
L

Lasse Reichstein Nielsen

Randell D. said:
Why would one use bitwise operators?

I would say that it should rarely be needed.

In C, you often had to fiddle with bits, since you did most
I/O-programming directly on the bits. You had to toggle bits
and implement your own bit vectors. It made perfect senst
to have bit-operations in such a low-level language.

In Javascript, you can implement a bit vector as an integer and use
bitwise operators. You could also make it an array of booleans and
create the methods you need. The latter scales better.

There are still cases, where integer arithmetic can more easily, or
just faster, be implemented with bitwise operations. I know there are,
I just can't remember any of them right now.

/L
 
J

Jeff North

|
| Why would one use bitwise operators? I can program in various languages in
| some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
| operators before, but never understood why anyone would use them - any real
| world examples or ideas? Examples follow (that I am reading in my Core
| JavaScript Guide 1.5).
|
| 15 & 9 yields 9 (1111 & 1001 = 1001)
| 15 | 9 yields 15 (1111 | 1001 = 1111)
| 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
| in addition there are AND,OR,XOR,NOT and left and right shifts which would
| only extend this post longer than nescessary...

I've just recently used such an example. I needed to set up some form
of security for different people accessing different web pages.
Instead of maintaining 12+ variables; I bitmapped the values into a
single variable. Now all I need to do is place some code like:
if( security_bits & CONST_dept_name )
and process from there.

I could also use
if( security_bits & (CONST_dnm1 + CONST_dnm2 + CONST_dnm3) )

This is server-side scripting. I can't see much benefit in using this
client-side.
 
R

Randell D.

Lasse Reichstein Nielsen said:
I would say that it should rarely be needed.

In C, you often had to fiddle with bits, since you did most
I/O-programming directly on the bits. You had to toggle bits
and implement your own bit vectors. It made perfect senst
to have bit-operations in such a low-level language.

In Javascript, you can implement a bit vector as an integer and use
bitwise operators. You could also make it an array of booleans and
create the methods you need. The latter scales better.

There are still cases, where integer arithmetic can more easily, or
just faster, be implemented with bitwise operations. I know there are,
I just can't remember any of them right now.

/L

I'm glad its a rarely used facility/function... I'm pretty sure I can get
along with javascript without it so that suites me fine.

Cheers
randell d.
 
R

Richard Cornford

Lasse Reichstein Nielsen said:
I would say that it should rarely be needed.

In C, you often had to fiddle with bits, since you did most
I/O-programming directly on the bits. You had to toggle bits
and implement your own bit vectors. It made perfect senst
to have bit-operations in such a low-level language.

The bitwise operators are available at the very low level of CPU
instructions which means that they are almost trivial to implement in
any language. It might be as much that as anything else that has them
finding their way into ECMA Script.

There are still cases, where integer arithmetic can more
easily, or just faster, be implemented with bitwise operations.
I know there are, I just can't remember any of them right now.

One application is integer division and multiplication by 2, 4, 8,.. etc
using the shift operators. I recently used - x = y >> 1 - as a division
by 2 with a floored result, though it is not the same as - x =
Math.floor(y/2) -, and it looks like I had rendered the entire
process unnecessary by the final version of that code.

Shift is also useful for splitting hex representations of RGB colors
(used because they translate easily from HTML and CSS) into their
component colors. That could be combined with bitwise AND to mask out
unwanted parts of a number (the alternative being y%256):-

var nRGBin = 0xFB3E1C;
var nR=(nRGBin>>16) & 0xFF;
var nG=(nRGBin>>8) & 0xFF;
var nB=nRGBin & 0xFF;

Richard.
 
V

VK

As it said, bitwises are low level, so they go right through the
interpreter's vertebral, not touching its brains :) So they are quick.

When I programmed EdLine (JavaScript-based text editor), I had some ugly
switches with about 30 cases in each for keyboard input. On a slow machine
it moved like an old god. Then I used bitwises instead to sort keycodes by
byte structure, and it run like a young poppy.

Talking about rarely used features: how long ago did you last time use
Math.acos() or Math.atan() ? :)
 
B

Bryan Field-Elliot

Randell said:
Why would one use bitwise operators? I can program in various languages in
some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
operators before, but never understood why anyone would use them - any real
world examples or ideas? Examples follow (that I am reading in my Core
JavaScript Guide 1.5).

15 & 9 yields 9 (1111 & 1001 = 1001)
15 | 9 yields 15 (1111 | 1001 = 1111)
15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
in addition there are AND,OR,XOR,NOT and left and right shifts which would
only extend this post longer than nescessary...

Their usefulness is very limited from a Javascript perspective; however
they do come in very handy once in a blue moon. One example is color
manipulation, I've used Javascript to take color settings from the
server, and brighten them up a bit... For example if a color code is in
the variable "color", then this will brigthen it by raising the high bit
of each color component (R, G, B):

color |= 0x808080;

(it's been a while but I'm pretty sure that was how we did it).
 
J

Jim Morrison

Randell said:
Why would one use bitwise operators? I can program in various languages in
some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
operators before, but never understood why anyone would use them - any real
world examples or ideas? Examples follow (that I am reading in my Core
JavaScript Guide 1.5).

15 & 9 yields 9 (1111 & 1001 = 1001)
15 | 9 yields 15 (1111 | 1001 = 1111)
15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
in addition there are AND,OR,XOR,NOT and left and right shifts which would
only extend this post longer than nescessary...

Here is a real word example:

The IP address called 10.0.0.1 is

(10 * 1<<24) + (0 * 1<<16) + (0 * 1<<8) + 1 = 167772161




Jim
 
S

Steve van Dongen

I'm sure there's a whole lot of things of questionable usefulness that
you can do with bit operations. Here's one... Swapping the contents
of two variables without using a temp variable.

var a = 15;
var b = 28;
a ^= b; // a = a XOR b
b ^= a; // b = b XOR a
a ^= b; // a = a XOR b

With memory as abundant as it is these days, I doubt people would do
something like that any more.

Randall's example is more interesting because it shows that a<<b is
equivalent to a * Math.pow(2, b). As someone already said, bit shifts
are a very simple operation and will be faster than multiplying or
dividing by multiples of 2.
Here is a real world example:

The IP address called 10.0.0.1 is

(10 * 1<<24) + (0 * 1<<16) + (0 * 1<<8) + 1 = 167772161

Continuing with the real world IP example, there's the method for
determining the network id portion of the ip address.

IP Address. . . . . . . . . . . . : 192.168.3.2
Subnet Mask . . . . . . . . . . . : 255.255.254.0

192.168.3.2 == 11000000 10101000 00000011 00000010
255.255.254 == 11111111 11111111 11111110 00000000

Network ID = IP Address & Subnet Mask
= 11000000 10101000 00000010 00000000
= 192.168.2.0

Regards,
Steve
 
R

Richard Cornford

Randall's example is more interesting because it shows that
a<<b is equivalent to a * Math.pow(2, b). As someone already
said, bit shifts are a very simple operation and will be
faster than multiplying or dividing by multiples of 2.
<snip>

The obvious next question is; if faster then by how much? So I created
some test pages to find out.

Comparing - Math.floor(S/2) - with - (S>>1) - seemed a reasonable
starting point. There are some differences as Math.floor rounds negative
numbers downwards while the shift moves them towards zero and the result
of the shift is a 32 bit signed integer so it cannot represent the same
integer range as the IEEE float that Math.floor outputs. The test page
is:-

<URL: http://www.litotes.demon.co.uk/js_speed/intDivBy2.html >

- and produced the results (taking Math.floor(S/2) as 100% on all tested
browsers for comparison):-

Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n/2) -- -- 100% -- --
(n>>1) 7.18% 22.94% 8.60% 16.28% 16.93%

Making the shift operation between 4 and 14 times faster.

That seemed a reasonable start so I compared - Math.floor(n)*2 - and -
(n<<1) :-

<URL: http://www.litotes.demon.co.uk/js_speed/intMulBy2.html >

- getting the results:-

Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n)*2 -- -- 100% -- --
(n<<1) 8.03% 21.82% 8.46% 26.19% 26.80%

Generally worse but not by much.

Looking at the above tests it occurred to me that any bitwise operator
was going to have the a similar effect to Math.floor (when the internal
ToInt32 function is called) if its input was a positive integer <= 31
bits, as might be the case when calculating screen co-ordinates with
floats and then converting the results to pixel co-ordinates. So any
bitwise operation that would not alter a 32 bit integer may be
substituted for Math.floor for those cases:-

<URL: http://www.litotes.demon.co.uk/js_speed/floorMethods.html >

Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n) -- -- 100% -- --
(n&0xFFFFFFFF) 14.40% 29.54% 14.42% 52.03% 24.25%
(n<<1)>>1 10.97% 56.04% 19.86% 39.70% 43.49%
(n|0) 8.23% 29.02% 10.64% 33.84% 24.33%

The double shift did not strike me as a good candidate as it further
reduces the maximum size of the integer (and involves two operations)
but as it performed generally badly it can be dismissed for that reason
alone (though I was surprised that it outperformed bitwise AND on
Mozilla 1.2). The bitwise OR zero operation is the clear winner at
between 3 and 12 times faster than Math.floor. Not a complete substitute
but if enough is known about the input it could be a fast alternative in
some cases.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,102
Messages
2,570,645
Members
47,245
Latest member
ShannonEat

Latest Threads

Top