Bits;
-
I have used a bit mask before but how does one extract individual bits. Say I wanted to extract bit 28 from 32 bit int, how do I do that? Thank You Bo Hunter
Try this:
int nvalue = 0xabcd; if ( nvalue & (1<<28) ) ; // bit 28 is set
Neville Franks, Author of ED for Windows www.getsoft.com and Surfulater www.surfulater.com "Save what you Surf" -
Try this:
int nvalue = 0xabcd; if ( nvalue & (1<<28) ) ; // bit 28 is set
Neville Franks, Author of ED for Windows www.getsoft.com and Surfulater www.surfulater.com "Save what you Surf" -
I have used a bit mask before but how does one extract individual bits. Say I wanted to extract bit 28 from 32 bit int, how do I do that? Thank You Bo Hunter
The other guys code works, and sometimes it is best. However consider the following #define FOO_MASK 0x01000000 //0000 0001 0000 0000 0000 0000 0000 0000 0000, mask for foo ... if(my_var && FOO_MASK) { .... This has the advantage that when I read your code I know instantly you are looking for foo, while the other guys code just gives me (1 >> 28). It takes a moment to realize that he is looking at bit 29, and still gives me no indication of what bit 29 is! Instead of the above you can also use bitfields: #pragma pack(1) struct myStruct { long foo :28; long bar :1; long baz :3; } #pragma pack() ... if(mystrct.bar) { ... This is compiler and CPU specific, but it works fairly often in the real world, and is more readable. If you must use the other guys code, please do it in a class, and only in one place. Then comment what is going on so when I come across it 10 years from now I can safely make a change.