Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How can I manipulate individual bits??
How can I manipulate individual bits??
✍: Guest
Bit manipulation is straightforward in C, and commonly done. To extract (test) a bit, use the bitwise AND (&) operator, along with a bit mask representing the bit(s) you're interested in:
value & 0x04
To set a bit, use the bitwise OR (| or |=) operator:
value |= 0x04
To clear a bit, use the bitwise complement (~) and the AND (& or &=) operators:
value &= ~0x04
(The preceding three examples all manipulate the third-least significant, or 2**2, bit, expressed as the constant bitmask 0x04.)
To manipulate an arbitrary bit, use the shift-left operator (<<) to generate the mask you need:
value & (1 << bitnumber)
value |= (1 << bitnumber)
value &= ~(1 << bitnumber)
Alternatively, you may wish to precompute an array of masks:
unsigned int masks[] =
{0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
value & masks[bitnumber]
value |= masks[bitnumber]
value &= ~masks[bitnumber]
To avoid surprises involving the sign bit, it is often a good idea to use unsigned integral types in code which manipulates bits and bytes.
2015-02-20, 1303👍, 0💬
Popular Posts:
How do I use a scriptlet to initialize a newly instantiated bean? A jsp:useBean action may optionall...
How To Merge Cells in a Row? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells If you wan...
Can you prevent a class from overriding ? If you define a class as “Sealed” in C# and “NotInheritab...
How To Build WHERE Criteria with Web Form Search Fields? - MySQL FAQs - Managing Tables and Running ...
What is the difference between Authentication and authorization? This can be a tricky question. Thes...