Featured post
c - The reason to use masking -
gcc 4.4.1 c89
i using api our previous programmer has produced. however, bit confused why masking in why.
what reason or
hex mask. , reason have ipev_error_mask or'ed ipev_start. why not have hex values?
#define ipev_mask 0x9000 #define ipev_error_mask (ipev_mask | 0x0800) #define ipev_open (ipev_mask | 0x01) #define ipev_start (ipev_mask | 0x02) #define ipev_media_fail (ipev_error_mask | ipev_start)
many suggestions,
not sure part unclear you, i'll explain everything.
first of all, they're bit flags. bit flags way of storing lot of boolean values inside single number. instance, typical 32-bit integer can store 32 boolean values. has dual advantages of being compact in memory, , being able pass around several values @ once. drawback is, of course, access single value have mess around bitwise operators. approach typically not used when dealing boolean values in code, used when storing values or passing them around. note while physically mash every boolean value available, typically use trick group related values (like status flags object or something).
now, there several traditions working bit flags. one, define constants descriptive names each bit. otherwise awkward fast. (hmm... did bit 17 mean...)
for another, use |
operator join several flags, though theoretically use +
operator. again has 2 reasons: 1 reason |
faster +
, more importantly, if accidentally include same flag twice, |
operator provide correct answer, while +
mess up.
this real danger, because in world of bit flags see not constants each bit, constants common combinations. |
operator can join these , sure result contain bits want, without worrying if might have set same bit twice.
thus come example:
#define ipev_mask 0x9000 #define ipev_error_mask (ipev_mask | 0x0800) #define ipev_open (ipev_mask | 0x01) #define ipev_start (ipev_mask | 0x02) #define ipev_media_fail (ipev_error_mask | ipev_start)
apparently have kind of "ipev" bit mask field somewhere, , these named constants bits. first constant ipev_mask
, sets bits number 15 , 12. there constant ipev_error_mask
, includes ipev_mask, , in addition sets bit 11. , on , forth.
the reason using these |
operations define constants (instead of writing hex literals), readability. compiler anyway optimize them fixed values, there won't bit calculations @ runtime. style of writing lets understand @ glance constant includes other constants. and, of course, if ever modify 1 of them, changes automatically reflect appropriate.
did make clearer? if have more questions, don't hesitate ask!
- Get link
- X
- Other Apps
Comments
Post a Comment