473,382 Members | 1,348 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Why bitwise operators?


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...

--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet?
Jul 20 '05 #1
11 8976
"Randell D." <yo**************************@yahoo.com> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
On Wed, 01 Oct 2003 22:18:53 GMT, in comp.lang.javascript "Randell D."
<yo**************************@yahoo.com> wrote:
|
| 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.
---------------------------------------------------------------
jn****@yourpantsbigpond.net.au : Remove your pants to reply
---------------------------------------------------------------
Jul 20 '05 #3

"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:7k**********@hotpop.com...
"Randell D." <yo**************************@yahoo.com> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'


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.
Jul 20 '05 #4
"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:7k**********@hotpop.com...
"Randell D." <yo**************************@yahoo.com> writes:
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.


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.

<snip>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.
Jul 20 '05 #5
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() ? :-)

Randell D. <yo**************************@yahoo.com> wrote in message
news:hpIeb.1632$pl3.1428@pd7tw3no...

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...

--
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet?

Jul 20 '05 #6
Randell D. wrote:
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).

--

Bryan Field-Elliot
http://netmeme.org

Jul 20 '05 #7
Yeah but what if you want to write a javascript NIM player ????????
:)
Jul 20 '05 #8
Randell D. wrote:
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 ...


There was a time -- coincidentally, the time during which I did my heaviest
duty software development (I'm retired now) -- when people actually cared
about how much room things took. Bitwise manipulation was essential
to using single bits in a byte to indicate different conditions,
preferences,
etc. For all I know to the contrary, this may still be important in
applications like cellphones and other smart appliances. It would certainly
be important to recovering data from older databases and in retaining
upwards compatability for older applications.

Jul 20 '05 #9


Randell D. wrote:
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




Jul 20 '05 #10
On Fri, 03 Oct 2003 03:27:59 GMT, Jim Morrison <do****@comcast.net>
wrote:


Randell D. wrote:
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'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
Jul 20 '05 #11
"Steve van Dongen" <st*****@hotmail.com> wrote in message
news:rb********************************@4ax.com...
<snip>
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_sp...orMethods.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.
Jul 20 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Michael B. Trausch | last post by:
I have a question regarding bitwise operators, I've been trying to figure this out for about two days now, and I just can't seem to get it. What I'm trying to do is use a variable to hold a bitmask...
4
by: Mike Hodkin | last post by:
As a beginning student of C++, books reference "bitwise operators" and give brief examples, but I have not read a good explanation of what they are used for. One reference mentioned that they are...
6
by: jas_lx | last post by:
The basic understanding of what bitwise operators (& ^ | >> << ) comes fairly simple, as long as one has a fundamental understanding of bits, bytes and binary. Having done some Win32...
2
by: Steve Summit | last post by:
-----BEGIN PGP SIGNED MESSAGE----- It's often explained that the reason for some of the imprecision in C's definition is so that C can be implemented on different kinds of machines -- say, those...
37
by: James Radke | last post by:
Hello, I found some code that I could use in my application on the web, but it is written in C#, and I would like to convert it to VB. And I am having problems with one section. Is there...
5
by: noridotjabi | last post by:
I'm learning to program in C and any tutorial or book that I read likes to briefly touch on birdies operators and then move on without giving any sort of example application of them. Call me what...
2
by: Mark Rae | last post by:
Hi, This isn't *specifically* an ASP.NET question, so I've also posted it in the ADO.NET group - however, it's not too far off-topic... Imagine a SQL Server 2005 database with a table with an...
29
by: Carl Banks | last post by:
Anyone with me here? (I know the deadline for P3 PEPs has passed; this is just talk.) Not many people are bit-fiddling these days. One of the main uses of bit fields is flags, but that's not...
16
by: Santhosh | last post by:
Hi to all, How the individual digits of a number can be obtained using the bitwise operators alone.Is it possible to do it ? If we have n = 34 Result has to be 3,4. Thanks a billion for...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.