Question

What is bitwise, and where does its purpose lie?

Asked by: jamesbcox1980

I'm trying to take the next step in programming, and for me that is to learn about bitwise operators.  I don't even know what bitwise is, save for the fact that it has to do with doing operations based on individual bits (as the name suggests).

Can someone please give me a starter on what it is (the basics) and where I'll be using it? I mainly do programming in JavaScript and PHP, but I'm about to start learning C++ and Java.  I have come across bitwise operators in JavaScript before, but had no idea what they meant or how I could possibly need them.  I saw a JS question a few weeks back that dealt with some encryption, so that seems really interesting.

Anyway, throw me a frickin' bone here!

Thanks!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-02 at 08:50:07ID24864235
Tags

bitwise

,

bitwise operators

Topics

JavaScript

,

C++ Programming Language

,

Java Programming Language

Participating Experts
7
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Detecting disabled JS in PHP
    Ok heres the scenario: I have a floating nav bar that reads $_SESSION['navtype'] to decide whether or not the user wants floating ("float") or fixed ("fixed") navigation. I need navtype to be set to "float" by DEFAULT, unless the user has JS di...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: CEHJPosted on 2009-11-02 at 08:52:30ID: 25721062

Take a look at this. Let me know if you need clarification on any bits(!) of it

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

 

by: jamesbcox1980Posted on 2009-11-02 at 08:57:54ID: 25721109

Lol... will do

 

by: jamesbcox1980Posted on 2009-11-02 at 09:02:44ID: 25721164

Ok, so that explains a bit about how to use the operators, but I'm at a loss as to what the purpose of them is.  What would be the purpose in bit shifting, inverting or playing with bits altogether?  Someone said in that page, if I don't know what bitwise is, I probably don't need it.  But that's the thing, I'm trying to explore another aspect of programming.

 

by: jkrPosted on 2009-11-02 at 09:26:33ID: 25721406

Also take a look at http://www.cprogramming.com/tutorial/bitwise_operators.html ("Bitwise Operators in C and C++: A Tutorial") - the purpose should become clear.

A bit more in-depth: http://www.codeproject.com/KB/cpp/bitbashing.aspx ("An introduction to bitwise operators"), which portraits the purpose as "The beauty of having bitwise operators is that you can use a BYTE, WORD or DWORD as a small array or structure. Using bitwise operators you can check or set the values of individual bits or even a group of bits.".

 

by: itsmeandnobodyelsePosted on 2009-11-02 at 09:37:39ID: 25721522

Maybe you'll have a look at http:Q_24814784.html

 

by: CEHJPosted on 2009-11-02 at 09:41:03ID: 25721561

Well here's an example:

You need to call a method that takes an char as a parameter: it wants a Unicode character encoded as UTF-16, let's say the Euro symbol. You, otoh, since the character takes up two bytes, have it as a byte array since you read it from a Socket.
You therefore need to convert byte[2] to char:


	byte[] euroBytes = { 32, (byte)172 };
	char euro = (char)((euroBytes[0] << 8) | (euroBytes[1] & 0xFF));
	System.out.println(euro);
	System.out.printf("%04x\n", (int)euro);
                                              
1:
2:
3:
4:
5:

Select allOpen in new window

 

by: tdlewisPosted on 2009-11-02 at 10:11:47ID: 25721889

'Bit' is short for 'binary digit'. All values in a computer are stored as a series of ones and zeros. For example, when a variable contains an integer or a character, the value is encoded as bits.

x = 12; // stored as 0000 1100, 1*8 + 1*4 + 0*2 + 0*1 = 12
x = 63; // stored as 0011 1111, 1*32 + 1*16+ 1*8 + 1*4 + 1*2 + 1*1 = 63
x = 'a';  // stored as 0110 0001, arbitrary value assigned by ANSI

When you perform a bitwise operation, you perform an action on the individual bits of the value stored in the variable.

You can perform a bitwise operation on any piece of data, but most commonly, such operations are performed on character data.

Hope that helps.

 

by: jamesbcox1980Posted on 2009-11-02 at 11:18:08ID: 25722642

Ok thanks, @jkr (http:#25721406).  That pretty much explains when I'll be using it.  I'm interested in looking into the encryption side of programming.  I still don't quite understand what shifting a byte stands to accomplish.  I'm trying to see the semi-big picture here.

@CEHJ (http:#25721561): Thanks for that example.

 

by: jkrPosted on 2009-11-02 at 11:33:49ID: 25722807

>> I'm interested in looking into the encryption side of programming.  I still
>> don't quite understand what shifting a byte stands to accomplish.

Well, a maybe-not-too-complex example on how bitwise operations come in handy is the MD5 Algorithm: http://en.wikipedia.org/wiki/MD5#Algorithm

 

by: trinitrotoluenePosted on 2009-11-02 at 18:39:04ID: 25725673

bitwise operations can perform masking and unmasking of individual bits, thats putting it very mildly. At the most basic level that is where they help out in Encryption.

for instance lets say you have a bit pattern as 101
you want to encrypt it as 111 and only you know the method to do this. to accomplish this you can bitwise OR 101 with 010 and you would get a 111.
On the other side when your encrypted pattern is received you will now have the intel to decrypt it and get the original pattern back.

These operators also come in very useful for device driver routines and low level firmware programming.



take a look at our previous post on this topic

http://www.experts-exchange.com/Programming/Languages/C/Q_24814784.html


also take a look at the following threads
http://stackoverflow.com/questions/1584122/c-c-using-bitwise-operators
http://bytes.com/topic/c/answers/219607-practical-usage-bitwise-operators

 

by: InternalStaticPosted on 2009-11-03 at 09:03:41ID: 25731037

I'll just give you a quick rundown on bits and why we use these strange "bitwise" operators. If I repeat anything the other experts have said, I apologize, as I don't have time to read all of their responses and adjust mine accordingly.
 
Quite often, we need to pass 'messages' from one object to another, and those 'messages' contain values that can only mean a set amount of things. For example, when we want to open a file, there are only a few set ways we can do this: write-only, read-only, or read-write (with some more optional stuff, such as whether or not to lock the file, etc). We could make an object that contained 4 boolean variables (one for read, write, read-write, and lock), but remember that a Boolean doesn't actually take up a single bit, as RAM doesn't allow such a layout of bits.
 
Also quite often, we need to drill messages from one place to another hundreds of times a second, and every bit counts, so we want to compact these messages to make them as lightweight as possible. This is when bit flags come in. We can combine the above 4 bits into a numeric value, and treat them as binary instead of numbers. For example, suppose you are the method who is acting on opening files, and you receive a message like this:
 
00000110
 
As you also know, we usually work in bytes (8 bits), so I padded on 5 extra zeros to the left. The 6th bit indicates read access, the 7th indicates write, and the last indicates lock. 0 means false, 1 means true, of course. So, if the 6th bit is on, we need read access. If the 6th AND 7th bits are on, we need read-write, and if the 8th bit is on, we need to lock the file. Easy, right? The above equates to 6 if you convert it from binary into a numeric value (which is what we, as humans, work with usually). There are six bitwise operators in most (if not all) langauges:
  Bitwise AND ( & )
Bitwise OR ( | )
Bitwise XOR ( ^ )
Bitwise Left Shift ( << )
Bitwise Right Shift ( >> )
Bitwise COMPLEMENT (Or NOT) ( ~ )

 
Each of these operators have unique properties, but they all have one thing in common: they operate on binary values. The first five operate on two binary values, while the last has a single operand, and thus only operates on one value. The first operator, Bitwise AND ( & ), will return true, or 1, if two corresponding bits are both true. For example, look at the following:
 
   1
& 1
1
 
Because those two bits were both true, the AND operation returned another true. However, the operators don't have to work one bit at a time. You can operate on a whole byte, or a whole short (16 bits), a whole 32-bit int, and so on. Usually, you only use this with booleans and non-floating point values. Take this for example (I'm just using 8 bits because I'm lazy, heh):
 
    0 1 1 0 0 1 1 0
& 1 0 1 1 0 1 1 1
    0 0 1 0 0 1 1 0
 
Now that you have an idea as to how bitwise operators work, I'll just explain the rest in general.
 
Bitwise OR returns true if either of the two bits are true. So, the same two binary values (above) OR'ed instead of AND'ed looks like this:
 

   0 1 1 0 0 1 1 0
|  1 0 1 1 0 1 1 1  
  1 1 1 1 0 1 1 1
 
The last of the three in this 'group' (that act using two like binary values) is XOR (Exclusive OR). It's the strangest; it returns true if one of corresponding bits are true, but the other is false. If both are true or both are false, it returns false.
 
    0 1 1 0 0 1 1 0
^  1 0 1 1 0 1 1 1  
    1 1 0 1 0 0 0 1
 
The next two related functions are left shift and right shift. It literally shifts bits to the left or right according to the number of bits. These two act strangely on signed/unsigned numbers, so I suggest searching this on Bing or Google or whatever you like to use.
 
Complement is the easiest. It just reverses the bits on each bit, so 0 becomes 1 and 1 becomes 0.
 
So how does this even converge into your programming career?! Well, these operators transform binary values according to certain 'algorithms'. So, let's say you have a set of flags and they mean seperate things. A certain bit being on means one thing, while the next means something else, etc. etc. How do we 'extract' these values and tell if the bits are on or off?! And how do we turn certain bits on and off? Usually, we use AND, OR, and XOR for manipulating flags.
 
To turn a certain flag off, you can take the value you wish to turn the flag off on and & it by the bit you want to turn off. You have to think in binary, but write code in decimal, so consider the following boolean expression:
 
(someFlags | 2) > someFlags
 
Assuming someFlags is a byte (remember, binary is laid out as 128 64 32 16 8 4 2 1 for a byte), when we OR it by 2, if the value gets larger, we know that the 2 bit was off in the original value. If OR'ing it keeps the value the same, we know that the 2 bit was already on.
 
If you need more help on this, I suggest going through the links other experts have posted. I think my post is quite long enough. However, if you'd like me to elaborate further, I would be happy to :)
 
Hope it helps,
Nate

 

by: FalmarriPosted on 2009-11-03 at 12:54:52ID: 25733499

As InternalStatic summed up pretty nicely. Bitwise operations are used extensively in digital logic. Things like shifting a bit is analogous to multiplying by 10 (or rather 2 as is the case in bitwise).

 

by: jamesbcox1980Posted on 2009-11-04 at 09:28:05ID: 31648938

Thanks guys.  All good answers, but chose these for relevance and content.

I can see a few instances where this might come in handy for working with my databases.  Also, I really want to start learning security.  I didn't realize bitwise was so important for speeding up the exchange of data.  I also never thought about the fact that when manipulating file permissions from my FTP server, I was manipulating the bits! (stored as an integer that is a representation of the 1011 style file attribute system)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...