regarding bitwise shift in "eventloop.h"

Mark Doliner mark at kingant.net
Wed Aug 1 01:39:26 EDT 2007


On Tue, 31 Jul 2007 22:17:47 -0700, Harry Tanama wrote
> Hi Experts,
> 
> I don't really understand the purpose of using bitwise left-shift in
> constant value of PurpleInputCondition enum.
> 
> typedef enum
> {
>     PURPLE_INPUT_READ  = 1 << 0,  /**< A read condition.  */
>     PURPLE_INPUT_WRITE = 1 << 1   /**< A write condition. */
> 
> } PurpleInputCondition;
> 
> Could we just use these method instead?
> 
> typedef enum
> {
>     PURPLE_INPUT_READ  = 1,  /**< A read condition.  */
>     PURPLE_INPUT_WRITE = 2   /**< A write condition. */
> 
> } PurpleInputCondition;

Yes, you could use those instead.  The reason we're using a bitwise shift is
that the values in that enum are used as a bitmask.  So, if you want to watch
for when a socket is both available for reading and available for writing,
then you would use PURPLE_INPUT_READ | PURPLE_INPUT_WRITE.

Since the values can be or'ed together, it's important that the bits don't
overlap.  If there were four PURPLE_INPUT_WHATEVERs instead of just two then
they would have the following binary values:
0001    1, or 1 << 0
0010    2, or 1 << 1
0100    4, or 1 << 2
1000    8, or 1 << 3

Using the bitwise shift just makes it easier on the programmer because he can
just increment by one when adding a new value to the enum instead of having to
remember to use the next power of two.

I guess the goal is to reduce programming mistakes.  It's debatable how much
this really helps.  Also, I imagine most preprocessors do the shifting such
that it doesn't happen at runtime.

-Mark

-Mark




More information about the Devel mailing list