| Start |
|---|
Toggling a bit C-style bit-manipulationA bit can be toggled using the XOR operator ( Using std::bitset |
Checking a bit C-style bit-manipulationThe value of the bit can be obtained by shifting the number to the right The right-shift operation may be implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If If we need the value of that bit directly in-place, we could instead left shift the mask: Either can be used as a conditional, since all non-zero values are considered true. Using std::bitset |
Set all bits C-style bit-manipulation(See here (opens new window) for an explanation of why this works and is actually the best approach.) Using std::bitset |
Remove rightmost set bit C-style bit-manipulationExplanation
|
Setting a bit C-style bit manipulationA bit can be set using the bitwise OR operator ( Using std::bitset
|
Clearing a bit C-style bit-manipulationA bit can be cleared using the bitwise AND operator ( Using std::bitset
|
Changing the nth bit to x C-style bit-manipulationUsing std::bitset
|
| Counting bits set The population count of a bitstring is often needed in cryptography and other applications and the problem has been widely studied. The naive way requires one iteration per bit: A nice trick (based on Remove rightmost set bit (opens new window) ) is: It goes through as many iterations as there are set bits, so it's good when The method was first proposed by Peter Wegner (in CACM (opens new window) 3 / 322 - 1960) and it's well known since it appears in C Programming Language by Brian W. Kernighan and Dennis M. Ritchie. This requires 12 arithmetic operations, one of which is a multication: This kind of implementation has the best worst-case behavior (see Hamming weight (opens new window) for further details). Many CPUs have a specific instruction (like x86's |
| Check if an integer is a power of 2 The Note that without the first part of the check ( |
| Bit Manipulation Application: Small to Capital Letter One of several applications of bit manipulation is converting a letter from small to capital or vice versa by choosing a mask and a proper bit operation. For example, the a letter has this binary representation The code for converting a letter to A letter is The result is RemarksIn order to use
References |
Read Article
https://develop.horje.com/learn/1434/reference