473,385 Members | 1,753 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,385 software developers and data experts.

Practical usage of bitwise operators.

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
using bitwise operators.

However, in all of my programming endevours and studies (including the
K&R book, Data Structures books, Stroustrup's book, Petzold's book, and
various Linux programming books), I have yet to come across any really
good, practical examples of using bitwise operators.

With C, of all languages, it helps tremendously to have practical,
meaningful examples of using the various constructs. Let's face it, C
syntax is intitially non-intuitive, and it's paradigms (pointers,
dynamic memory allocation, bitwise operators, and the like), can be
confusing at times and a source of hard to detect bugs, even for
experienced programmers.

So, does anyone have good practical examples of using bitwise
operators?

Nov 14 '05 #1
6 8950
jas_lx <ja****@yahoo.com> wrote:
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
using bitwise operators. However, in all of my programming endevours and studies (including the
K&R book, Data Structures books, Stroustrup's book, Petzold's book, and
various Linux programming books), I have yet to come across any really
good, practical examples of using bitwise operators. With C, of all languages, it helps tremendously to have practical,
meaningful examples of using the various constructs. Let's face it, C
syntax is intitially non-intuitive, and it's paradigms (pointers,
dynamic memory allocation, bitwise operators, and the like), can be
confusing at times and a source of hard to detect bugs, even for
experienced programmers. So, does anyone have good practical examples of using bitwise
operators?


There are a lot of examples where using them is quite convenient.
E.g. toggling a bit of an unsigned char that's only used as a
boolean value can be quite simple by writing e.g.

is_used ^= 1;

instead of

if ( is_used )
is_used = 0;
else
is_used = 1;

or, a bit shorter,

is_used = is_used ? 0 : 1;

They are, as you write, often used to store a set of binary states
in a single variable. But most often bitwise operators are used (at
least to my of course limited experience) when you have to deal with
hardware on a low level. Then they are extremely handy and much
easier to read and understand than a replacement by with lots of
multiplications, modulo operations etc. You often have to set or
reset a single or a small number of bits in values that you read
from hardware registers and then write them back to initiate a
certain action of a device. Here's a line, more or less picked at
random from a driver I wrote for D/A-converter card

AI_Command_1 &= ~ ( AI_SC_Arm | AI_SI_Arm | AI_SI2_Arm );

AI_Command_1 is a variable where I store the value I will have to
write later to a register of the board (the AI Command Register 1)
and which I use to keep a track of what the driver has written to
it before to be able to remember in which state the board is. The
things on the right side are defined (to make the program readable)
as

#define AI_SI2_Arm ( 1 << 12 )
#define AI_SI_Arm ( 1 << 10 )
#define AI_SC_Arm ( 1 << 6 )

So AI_SI2_Arm stands for the bit 12 of the register etc. And the
whole line above is meant to reset (switch off) these bits in the
representation of the (16-bit wide) register. Later I am going to
write that value to the register to stop the board, which is just
doing a data acquisition (AI stands for analog input and the board
is repeatedly converting an input voltage at a certain rate, by
resetting the bits the frequency gets set to 0 Hz and thus the con-
version is effectively stopped).

If you look at such kind of programming you will find lots and lots
of lines like that, basically whenever you have to deal with the
hardware. If you look at any documentation about the hardware level
programming of a device you will immediately see what the bitwise
operators are good for. An example where you can see them used in
lots of places are e.g. the low level drivers in the Linux kernel.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #2
On 7 Dec 2004 16:13:45 -0800, "jas_lx" <ja****@yahoo.com> wrote:
The basic understanding of what bitwise operators (& ^ | >> << ) comes
fairly simple, as long as one has a fundamental understanding of bits,
bytes and binary.
....
So, does anyone have good practical examples of using bitwise
operators?


Bitwise operators can be practically used to pack multiple boolean values
into a single char (or even an int on some playforms.) Some games have
been known to do this. As an example, one game uses the following:

/*
* Chest trap flags (see "tables.c")
*/
#define CHEST_LOSE_STR 0x01
#define CHEST_LOSE_CON 0x02
#define CHEST_POISON 0x04
#define CHEST_PARALYZE 0x08
#define CHEST_EXPLODE 0x10
#define CHEST_SUMMON 0x20

If a player attempts to open a chest, the bitwise operators are used on one
of the fields describing the object to check if these traps will activated.
In theory, any combination can result depending on where the chest was
found.
Nov 14 '05 #3
jas_lx wrote:
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
using bitwise operators.

However, in all of my programming endevours and studies (including the
K&R book, Data Structures books, Stroustrup's book, Petzold's book, and
various Linux programming books), I have yet to come across any really
good, practical examples of using bitwise operators.

With C, of all languages, it helps tremendously to have practical,
meaningful examples of using the various constructs. Let's face it, C
syntax is intitially non-intuitive, and it's paradigms (pointers,
dynamic memory allocation, bitwise operators, and the like), can be
confusing at times and a source of hard to detect bugs, even for
experienced programmers.

So, does anyone have good practical examples of using bitwise
operators?


Have a look at the well-known Crafty chess engine
http://www.crafty-chess.com/

Its
- written in C
- represents pieces (eg white pawns) as 64 bit integers, one bit for each
square
- conputes moves using bit operations
- is just about all bit fiddling

gtoomey
gtoomey
Nov 14 '05 #4
On 7 Dec 2004 16:13:45 -0800, "jas_lx" <ja****@yahoo.com> wrote in
comp.lang.c:
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
using bitwise operators.

However, in all of my programming endevours and studies (including the
K&R book, Data Structures books, Stroustrup's book, Petzold's book, and
various Linux programming books), I have yet to come across any really
good, practical examples of using bitwise operators.

With C, of all languages, it helps tremendously to have practical,
meaningful examples of using the various constructs. Let's face it, C
syntax is intitially non-intuitive, and it's paradigms (pointers,
dynamic memory allocation, bitwise operators, and the like), can be
confusing at times and a source of hard to detect bugs, even for
experienced programmers.

So, does anyone have good practical examples of using bitwise
operators?


Want a real world example? Take a look at
http://jk-technology.com/C_Unleashed/code_list.html, which contains
GPL source code from a chapter I wrote in a book about C some years
ago.

The first 6 files listed, Chap18.txt through lj300.c use quite a bit
of bitwise operations. They include code for encoding a file
representing a black-and-white bit-mapped image into standard T.4
encoding for a FAX machine, and the reverse. If you want the text of
the article you'll have to buy a copy of the book, because the
publisher owns that, but the files on this page are all GPL.

Realistically, in addition to dealing with hardware devices, bitwise
operations are extensively used in data compression, data encryption,
data checking, and all sorts of image processing, including JPEG and
MPEG formats.

There are many other uses as well.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #5
Je***********@physik.fu-berlin.de writes:
jas_lx <ja****@yahoo.com> wrote:

[...]
So, does anyone have good practical examples of using bitwise
operators?


There are a lot of examples where using them is quite convenient.
E.g. toggling a bit of an unsigned char that's only used as a
boolean value can be quite simple by writing e.g.

is_used ^= 1;

instead of

if ( is_used )
is_used = 0;
else
is_used = 1;

or, a bit shorter,

is_used = is_used ? 0 : 1;


I'm afraid that's not a good example. If is_used is intended to store
only a single boolean value, a better way to negate it is:

is_used = !is_used;

Your "is_used ^= 1;" only toggles the low-order bit. If is_used
happens to have a value other than 0 or 1, the logically true value
will remain logically true.

If you can guarantee that you'll never store a value other than 0 or 1
in is_used, you can get away with operating on just the low-order bit,
but that's a difficult (and unnecessary) guarantee to make. Something
as innocuous as

is_used = isalpha(some_char);

can break it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
Wow! These are all great examples! Thanks everyone for the responses.

The AI_Command example for writing to a board register is awesome, as
are the chess game, the video game, and the example from "C
Unleashed". The last one I'm going to try to compile, alter (for
experimentation), and compile again, then run it - should be fun!
Thanks everyone.

Nov 14 '05 #7

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...
11
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...
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...
15
by: Capstar | last post by:
Hi NG, I have a question about the usage of bitfileds in a structure. for instance: struct pcard { unsigned pips : 4; unsigned suit : 2; };
34
by: Christopher Benson-Manica | last post by:
I'm trying to compute the absolute value of an integer using only bitwise operators... int x; sscanf( "%d", &x ); printf( "%d\n", (x^((~((x>>31)&1))+1)) + ((x>>31)&1) ); That works, but it...
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...
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...
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: 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
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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...
0
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,...

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.