473,915 Members | 5,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bitwise Operators: Aplication

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 these were necessary to learn or even adequately
describe what they do. Therefor any explanation or recommendation of
the bitwise operators would be greatly appreciated by me. Thanks in
advanced.
Nori

**If I'm off topic tell me**

Apr 24 '06 #1
5 5807
AG
In typical C coding, I never use either of these commands. But it is
common in microprocessor applications that you would look at just one
or two bits from a register. To look at just one or two bits at a time
is called masking. Suppose you have a byte-sized register (reg) but
you only need to look at two bits (bit3 and bit7). The following
bitwise AND statement

k = reg & %10001000

will exclude all bits except bit3 and bit7, no matter what value is in
reg.

k=%X000X000

I hope this helps.

Apr 24 '06 #2
On 2006-04-24, no*********@gma il.com <no*********@gm ail.com> wrote:
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 these were necessary to learn or even adequately
describe what they do.


What they do is operate on their operands one bit at a time:

uint32_t a = 42;
uint32_t b = 87;

In binary, these two numbers look like this:

000000000000000 000000000001010 10
000000000000000 000000000010101 11

Now, we can "AND" bits one at a time:

000000000000000 000000000001010 10 &
000000000000000 000000000010101 11
--------------------------------
000000000000000 000000000000000 10
(we get a 1 in each column where both inputs are 1)

which is 2 in decimal, or "OR" bits one at a time:

000000000000000 000000000001010 10 |
000000000000000 000000000010101 11
--------------------------------
000000000000000 000000000011111 11
(we get a 1 in each column where either input is 1)

Which is 127 in decimal.

What do you use them for? Among other things, quite often for
collections of boolean values, one or more of which may be true e.g.:

#define BIG 1U
#define FURRY (1U << 1)
#define STRIPED (1U << 2)
#define SPOTTED (1U << 3)
#define EVERYTHING (BIG | FURRY | STRIPED | SPOTTED)

uint32_t leopard = BIG | FURRY | SPOTTED;
uint32_t tiger = BIG | FURRY | STRIPED;
uint32_t mouse = FURRY;
uint32_t zebra = BIG | STRIPED;

Then you can do various things, like test for presence of a property:

if (animal & FURRY)

or for presence of either one out of two properties:

if (animal & (FURRY | SPOTTED))

etc.

You can set a property like this:

animal |= FURRY;

or unset one like this:

animal &= ~FURRY;

and other things.

Exercise: how to toggle a flag?
Apr 24 '06 #3

<no*********@gm ail.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
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 these were necessary to learn or even adequately
describe what they do. Therefor any explanation or recommendation of
the bitwise operators would be greatly appreciated by me. Thanks in
advanced.
Nori

**If I'm off topic tell me**

Bitwise AND and OR are very useful for defining a flag variable.
Let's say I have a generic menu-builder function for, say, text editing:
Widget EditMenu( Widget parent, int flag );

Now in that function I can do something like:
if ( flag & CUT ) {
/* include CUT menu item */
}

if ( flag & COPY ) {
/* include COPY item */
}
.... etc.
where I have defined:
#define CUT 1
#define COPY 2
#define PASTE 4
#define CAPITALIZE 8
... etc (or could use shift operators to define these flag items.

Then I call my menu function:
Widget menu = EditMenu( parent, CUT | COPY | PASTE );
the above would create my menu with those three items.
I could also call it as:
Widget menu = EditMenu( parent, CUT | CAPITALIZE );
to only include CUT and CAPITALIZE functionality.

This is only one of a multitude of uses for these operators.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Apr 24 '06 #4
AG wrote:

Please provide context. See http://clc-wiki.net/wiki/Intro_to_clc for
information about this group and how to use Google to do the right thing.
In typical C coding, I never use either of these commands. But it is
common in microprocessor applications that you would look at just one
or two bits from a register. To look at just one or two bits at a time
is called masking.
True. It is also used when dealing with various communications protocols
and in lots of other places.

<OT>
Masking to select mode bits from one of the fields stat produces on *nix
is one such other instance.
</OT>
Suppose you have a byte-sized register (reg) but
you only need to look at two bits (bit3 and bit7). The following
bitwise AND statement

k = reg & %10001000

will exclude all bits except bit3 and bit7, no matter what value is in
reg.

k=%X000X000

I hope this helps.


It won't. I don't know (or want to know) what language it is but it
isn't C. I'm guessing that whatever language it is uses % to introduce
binary literals, but standard C (which is what we deal with here) has no
support for binary literals. Bit masks are generally specified in hex,
although there is nothing to stop you using octal or even decimal should
you chose.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
Apr 24 '06 #5

<no*********@gm ail.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
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 these were necessary to learn or even adequately
describe what they do. Therefor any explanation or recommendation of
the bitwise operators would be greatly appreciated by me. Thanks in
advanced.


The bitwise operators allow you to set, clear, invert, and shift bits in a
value. You may need to do this for many situations: such as programming
hardware registers, graphics, encryption, or extracting an error code.

bitwise or, | , allows you to set bits, any bits in the "oring" value which
are one get set
bitwise and, &, allows you to clear bits, any bits in the "anding" value
which are zero get cleared
bitwise xor, ^, allows you to invert bits, any bits in the "xoring" value
which are set get inverted
bitwise negation,~, allows you to invert all bits, all bits in the "noting"
value are inverted
left bitshift, <<, allows you to shift bits left
right bitshift, >>, allows you to shift bits right

Let's say you want to convert an ASCII unsigned char from lower case to
upper case. The lower case values are +32 above the uppercase values. 32
is nicely expressed as 0x20 hex or 00100000 binary. To convert 'a' to 'A",
we'd use the bitwise and to clear that single bit (bit 5):

val='a';
val&=~0x20; /* 'a' becomes 'A' in ASCII */
/* ~0x20 is 11011111, bit is zero to clear */
/* 'a' is 0x61 hex or 01100001 binary */
/* 'A' is 0x41 hex or 01000001 binary */

To convert 'A' back to 'a', we'd use the bitwise or to set that single bit (
bit 5):

/* val='A'; from above */
val|=0x20; /* 'A' becomes 'a' in ASCII */
/* 0x20 is 00100000, bit is one to set */
/* 'A' is 0x41 hex or 01000001 binary */
/* 'a' is 0x61 hex or 01100001 binary */
HTH,

Rod Pemberton
Apr 24 '06 #6

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

Similar topics

9
2538
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...
11
9040
by: Randell D. | last post by:
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...
4
2494
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
8986
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
3476
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
11095
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)
2
2757
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
5965
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
3022
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
10923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10542
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
9732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7256
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5943
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4778
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
4344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3368
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.