Page 1 of 1

PostPosted: Thu Oct 02, 2003 6:30 pm
by cable_guy_67
As I learn to get comfortable programming for the palm with pocketC the more I find I know so little. Right now I am trying to find info on how to really understand the bit-wise operators, namely &,|,^,<< and >>. I understand logically how they work. At a bitwise level however I fail to fully grasp the concept and how it could be applied in the real world.

Example: If I wanted to use a piece of data as a series of flags or switches, how would I store them and then read them later at the 1-0 level. It could be useful if you have the need for lots of variables that will only have a yes or no value stored in it.

If anyone can steer me to some documentation that actually explains this please let me know. The PocketC documentation is thin there. My book on C is the same way. I would like to be able to use a single variable to store a multitude of 1's and 0's to be used as flags.

Thanks in advance,


PostPosted: Thu Oct 02, 2003 11:12 pm
by wolfgang

here's how (an integer si 4 bytes = 32 bits; bit 0 is the least significant):

int myint;
int n, mybit;

Set a specific bit (bit no. n, n = 0..31) to 1 and leave all other bits unchanged:

myint = myint | (1 << n);

Set a specific bit (bit no. n, n = 0..31) to 0 (i.e. clear the bit) and leave all other bits unchanged:

myint = myint & ~(1 << n);

Read a specific bit (bit no. n, n = 0..31) from an integer:

mybit = (myint & (1 << n)) >> n;

This gives either 0 (bit cleared) or 1 (bit set) as result. If you only want to use the flag in an "if" clause, then you care only about the bit being 0 or being not zero, hence you can simplify:

Check if bit n is set:

if (myint & (1 << n)) { ... do something ... }

Check if bit n is cleared:

if (!(myint & (1 << n))) { ... do something ... }

You can simplify (and speed up) the code when the bit number is not a variable, e.g. to set bit 7,

myint = myint | (1 << 7);

can be changed to

myint = myint | 0x00000080;

This way you can also set or clear several bits at once, e.g. to set bits 8 through 15,

myint = myint | 0x0000ff00;


Composing music on the PocketPC! -

PostPosted: Fri Oct 03, 2003 9:26 am
by cable_guy_67
Thanks for the info and code. That was exactly what I needed to clear things up. Such a simple concept but the code I have been working with only used this method to set the least significant. I now GET it. BTW, I have used your tutorials on your site while I was learing, they have always been helpful.