Archived

This topic is now archived and is closed to further replies.

io

bitwise comparisons help

Recommended Posts

io    122
i was reading "tricks of the windows programming gurus"(p.152), and came across an example i don''t quite grasp. when the author was processing a WM_CHAR message, he handled it like this: ---------------------------------- #define ALT_STATE_BIT 0x20000000 (in event handler, gets the state vector, a 32 bit value) int key_state = lparam; if(key_state & ALT_STATE_BIT) do whatever; ---------------------------------- the 29th bit of the state vector is the alt key; what he''s testing for so my question is: 0x20... is a hex value, so how does the comparison to the 29th bit work? keep in mind i''m not experienced in using bitwise comparisons =).

Share this post


Link to post
Share on other sites
mnansgar    421
It''s actually exactly as you say. Indeed, 0x20000000 is a hex value, but if you convert it to binary then the 29th bit is set, so when you AND it with the key_state, it will return positive if the 29th bit is set. An easy way to test this is just to open Windows Calculator, turn on the Scientific mode, then you''ll notice the Hex->Binary converters in the upper left.

Mike

Share this post


Link to post
Share on other sites
mrhollow    136
The answer lies in the fact that 0x20000000 comes out to:

100000000000000000000000000000

(That's 29 zeros)

The (&) and operation only sets a bit if both the mask (in this case 1 with 29 zeros) and the value being tested have a one in that position.

i.e. :


100000000000100000000000001000
& 100000000000000000000000000000
------------------------------------------------
= 100000000000000000000000000000


This would mean that if the 29th bit is a 1, the expression will come out true.

The best thing I can think of to learn more, is to read up on base (i.e. base 10 - our decimal system, base 2 - binary, base 16 hex).

Hope this was clear enough.

Cheerio,
Aaron

Edited by - mrhollow on July 2, 2001 6:35:33 PM

Share this post


Link to post
Share on other sites
Oluseyi    2103
One hex digit is equivalent to four binary digits (bits). This is because 16 is the fourth power of 2.

Therefore 16n = (24)n = 24n.
Also, an = S(k = 1, n-1)ak + 1

So 229 = 1629/4
29/4 = 7.25 = 7 + 1/4
=>167 + 1/4 = 167 + 161/4
=>167 + 2

Adding 2 spills the value to the next (eight bit).


Edited by - Oluseyi on July 2, 2001 6:39:58 PM

Share this post


Link to post
Share on other sites