-
January 19th, 2011, 03:48 AM
#1
Using Bitmasks
Hi,
I am trying to learn C++ and I don't know how to use bitmasks properly.
if( u & integer == 0 ) return 0;
else return 1;
I think I don't understand what the bitmask is actually doing. Can someone explain what this code is doing?
Thanks.
-
January 19th, 2011, 04:07 AM
#2
Re: Using Bitmasks
Victor Nijegorodov
-
January 19th, 2011, 04:23 AM
#3
Re: Using Bitmasks
Thanks, I have been reading around some what about it.
Do you know what this is doing?
#define BIT_OP( n ) ( ((TStruct)1) << n )
if (TStruct & BIT_OP(2) == 0)
Thanks.
-
January 19th, 2011, 04:38 AM
#4
Re: Using Bitmasks
Originally Posted by bobo01
Code:
#define BIT_OP( n ) ( ((TStruct)1) << n )
I guess it is a macro that:
- casts 1 to the TStruct type
- then shifts it n bits left
Originally Posted by bobo01
Code:
if (TStruct & BIT_OP(2) == 0))
It makes bitwise AND-expression of
TStruct value
and
the 1 casted to the TStruct type and shifted 2 bits left.
Victor Nijegorodov
-
January 19th, 2011, 04:43 AM
#5
Re: Using Bitmasks
Thanks, that is what I was thinking. I'm still stuck on this part:
"casts 1 to the TStruct type"
What does that mean?
-
January 19th, 2011, 04:47 AM
#6
Re: Using Bitmasks
Victor Nijegorodov
-
January 19th, 2011, 11:06 AM
#7
Re: Using Bitmasks
Originally Posted by bobo01
Thanks, that is what I was thinking. I'm still stuck on this part:"casts 1 to the TStruct type" What does that mean?
It means that we have an integer 1 (i. e. only the least significant bit is 1 and all other bits 0) that was casted to type TStruct. With a cast the type of the result in the parantheses was looked on - by the compiler - as a TStruct after. TStruct could be a typedef of an unsigned integer type or - more likely - it is a structure that has an int as first - or only - member. The point why anyone should do something like this is that on both sides of an bitwise AND using the operator & you need the same (kind of) type or the compiler would complain. So you normally can't compare a structure with an integer. The cast turns an integer to a TStruct which has all bits zero beside of that which which was set by the shift operation. Hence, the result of the '&' operation evaluates to something different to 0 (FALSE) if and only if the left operand has the same bit set to 1 what means that the first member of the struct TStruct (or a further member if the first member has less bits) has the specified bit set.
The only what doesn't fit to the above is that the left operand also was called 'TStruct' though
Code:
struct TStruct TStruct;
is a valid construct in C.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|