![]() ![]() In other words, it simply creates a field of 0's with a 1 at the specified All this does is create a mask with a single bit onĪnd which will work with any integer type. The common expression that you seem to be having problems with in all of these is "(1L << (posn))". #define BitTst(arg,posn) BOOL((arg) & (1L << (posn))) It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation. (number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x. It's generally a good idea to use unsigned types for portable bit manipulation. Number ^= (-newbit ^ number) & (1UL << n) Or unsigned long newbit = !!x // Also booleanize to force 0 or 1 number ^= (-(unsigned long)x ^ number) & (1UL << n) To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation. ![]() If x has some other value, you get garbage. Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation: number ^= (-x ^ number) & (1UL << n) īit n will be set if x is 1, and cleared if x is 0. That will put the value of the nth bit of number into the variable bit. Use the bitwise OR operator ( |) to set a bit. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |