473,706 Members | 4,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 9023
"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.javas cript "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****@yourpant sbigpond.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@pd7tw 3no...

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

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

Similar topics

9
2531
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 of 'flags' for users on a website. The function below is supposed to be a search function for one of those flags in a particular thing. The idea is that when something calls userId(), it should get to see what type of user flags that are...
4
2485
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 used in hardware programming. Are they used very often in routine C/C++ programming, and what for? thanks, MJH
6
8979
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 programming in straight C, the Win32 API sends windows messages to applications with various settings stored in bit fields, in which case changing the settings of the message is a matter of using the bitwise operators. This was a good practical example of...
2
3466
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 with 2's complement, 1's complement, or sign-magnitude arithmetic. But the followup remark is sometimes also made that the choice of arithmetic isn't completely unconstrained, since the bitwise operators seem to presume a base-2 machine.
37
11059
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 anyone that could tell me how to convert these two things? 1)
5
5794
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 you will but I cannot seem to see the purpose for bitwise operators. Especially the operators bitwise OR ( | ) and bitwise AND ( & ), I'm just not getting it. I have searched around and really haven't found anything that gave explanation to why...
2
2750
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 int column used for bitwise data - you know the sort of thing... 0, 1, 2, 4, 8, 16 etc intBitwise strName ----------------------
29
5948
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 often done in Python because of keyword arguments and dicts, which are lot more versatile. Another major use, talking to hardware, is not something oft done in Python either. It seems like this occasional usage wouldn't justify having built-in...
16
3001
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 your reply in advance.
0
8779
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8695
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9048
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4708
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3142
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2499
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2089
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.