Multisim 10.0.1 (latest) Multisim 11.0.2 Multisim 9.0.155. No specific info about version 8.0. Please visit the main page of Multisim on Software Informer. Editorial review: Read a full review. Screenshots (4) 2 awards.
Ontario Department of Lands and Forests: Resource Management Report Legislative Assembly of Ontario: Official Report of Debates (Hansard) Workplace Safety and Insurance Board and Workers' Compensation Appeals Tribunal Annual Reports Report of the Wartime Prices and Trade Board Annual Departmental Reports of the Dominion of Canada Journaux de la Chambre Communes du Canada avec l'Annexes my. What’s New with LabVIEW Developer Days? Framework is and key points to think about when choosing one. But I Heard T hat LabVIEW Does Not Work W ith Git or Hg.
Activetoday
JL22103,09533 gold badges1111 silver badges3737 bronze badges
JeffVJeffV20.9k2828 gold badges9090 silver badges112112 bronze badges
27 Answers
Use the bitwise OR operator (
|
) to set a bit.That will set the
n
th bit of number
. n
should be zero, if you want to set the 1
st bit and so on upto n-1
, if you want to set the n
th bit.Use
1ULL
if number
is wider than unsigned long
; promotion of 1UL << n
doesn't happen until after evaluating 1UL << n
where it's undefined behaviour to shift by more than the width of a long
. The same applies to all the rest of the examples.Use the bitwise AND operator (
&
) to clear a bit.That will clear the
n
th bit of number
. You must invert the bit string with the bitwise NOT operator (~
), then AND it.The XOR operator (
^
) can be used to toggle a bit.That will toggle the
n
th bit of number
.You didn't ask for this, but I might as well add it.
To check a bit, shift the number n to the right, then bitwise AND it:
That will put the value of the
n
th bit of number
into the variable bit
.Setting the
n
th bit to either 1
or 0
can be achieved with the following on a 2's complement C++ implementation:Bit
n
will be set if x
is 1
, and cleared if x
is 0
. If x
has some other value, you get garbage. x = !!x
will booleanize it to 0 or 1.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.or
It's generally a good idea to use unsigned types for portable bit manipulation.
or
(number & ~(1UL << n))
will clear the n
th bit and (x << n)
will set the n
th bit to x
.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.
Jeremy RutenJeremy Ruten131k3434 gold badges160160 silver badges185185 bronze badges
Using the Standard C++ Library:
std::bitset<N>
.Or the Boost version:
boost::dynamic_bitset
.There is no need to roll your own:
The Boost version allows a runtime sized bitset compared with a standard library compile-time sized bitset.
Peter Mortensen14.4k1919 gold badges8888 silver badges117117 bronze badges
Martin YorkMartin York206k6969 gold badges274274 silver badges495495 bronze badges
The other option is to use bit fields:
defines a 3-bit field (actually, it's three 1-bit felds). Bit operations now become a bit (haha) simpler:
To set or clear a bit:
To toggle a bit:
Checking a bit:
This only works with fixed-size bit fields. Otherwise you have to resort to the bit-twiddling techniques described in previous posts.
FerruccioFerruccio82.6k3535 gold badges202202 silver badges287287 bronze badges
I use macros defined in a header file to handle bit set and clear:
It is sometimes worth using an
enum
to name the bits:Then use the names later on. I.e. write
to set, clear and test. This way you hide the magic numbers from the rest of your code.
Other than that I endorse Jeremy's solution.
jfs285k8484 gold badges620620 silver badges11851185 bronze badges
dmckeedmckee81.5k2121 gold badges119119 silver badges213213 bronze badges
From snip-c.zip's bitops.h:
OK, let's analyze things..
The common expression that you seem to be having problems with in all of these is '(1L << (posn))'. All this does is create a mask with a single bit onand which will work with any integer type. The 'posn' argument specifies theposition where you want the bit. If posn0, then this expression willevaluate to:
If posn8, it will evaluate to:
In other words, it simply creates a field of 0's with a 1 at the specifiedposition. The only tricky part is in the BitClr() macro where we need to seta single 0 bit in a field of 1's. This is accomplished by using the 1'scomplement of the same expression as denoted by the tilde (~) operator.
Once the mask is created it's applied to the argument just as you suggest,by use of the bitwise and (&), or (|), and xor (^) operators. Since the maskis of type long, the macros will work just as well on char's, short's, int's,or long's.
The bottom line is that this is a general solution to an entire class ofproblems. It is, of course, possible and even appropriate to rewrite theequivalent of any of these macros with explicit mask values every time youneed one, but why do it? Remember, the macro substitution occurs in thepreprocessor and so the generated code will reflect the fact that the valuesare considered constant by the compiler - i.e. it's just as efficient to usethe generalized macros as to 'reinvent the wheel' every time you need to dobit manipulation.
Unconvinced? Here's some test code - I used Watcom C with full optimizationand without using _cdecl so the resulting disassembly would be as clean aspossible:
----[ TEST.C ]----------------------------------------------------------------
----[ TEST.OUT (disassembled) ]-----------------------------------------------
----[ finis ]-----------------------------------------------------------------
Felipe Augusto2,58844 gold badges1414 silver badges3232 bronze badges
yogeeshyogeesh
Use the bitwise operators:
&
|
To set last bit in
000b
:To check last bit in
foo
:To clear last bit in
foo
:I used
AzeemXXXb
for clarity. You'll probably be working with HEX representation, depending on the data structure in which you're packing bits.3,21444 gold badges1212 silver badges2424 bronze badges
nsandersnsanders9,36822 gold badges3434 silver badges4545 bronze badges
For the beginner I would like to explain a bit more with an example:
Example:
The
&
operator is used check the bit:Toggle or Flip:
|
operator: set the bit14.4k1919 gold badges8888 silver badges117117 bronze badges
kapildditkapilddit91544 gold badges1313 silver badges3434 bronze badges
Here's my favorite bit arithmetic macro, which works for any type of unsigned integer array from
unsigned char
up to size_t
(which is the biggest type that should be efficient to work with):To set a bit:
To clear a bit:
To toggle a bit:
To test a bit:
etc.
R.R.Multisim 10 Ith Serial Key Code
163k2929 gold badges276276 silver badges589589 bronze badges
The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.
You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.
You can then read, write, test the individual values as before.
RoddyRoddy46.8k3535 gold badges148148 silver badges245245 bronze badges
As this is tagged 'embedded' I'll assume you're using a microcontroller. All of the above suggestions are valid & work (read-modify-write, unions, structs, etc.).
However, during a bout of oscilloscope-based debugging I was amazed to find that these methods have a considerable overhead in CPU cycles compared to writing a value directly to the micro's PORTnSET / PORTnCLEAR registers which makes a real difference where there are tight loops / high-frequency ISR's toggling pins.
For those unfamiliar: In my example, the micro has a general pin-state register PORTn which reflects the output pins, so doing PORTn |= BIT_TO_SET results in a read-modify-write to that register. However, the PORTnSET / PORTnCLEAR registers take a '1' to mean 'please make this bit 1' (SET) or 'please make this bit zero' (CLEAR) and a '0' to mean 'leave the pin alone'. so, you end up with two port addresses depending whether you're setting or clearing the bit (not always convenient) but a much faster reaction and smaller assembled code.
John UJohn U1,68122 gold badges1717 silver badges3232 bronze badges
Check a bit at an arbitrary location in a variable of arbitrary type:
Sample usage:
Notes:This is designed to be fast (given its flexibility) and non-branchy. It results in efficient SPARC machine code when compiled Sun Studio 8; I've also tested it using MSVC++ 2008 on amd64. It's possible to make similar macros for setting and clearing bits. The key difference of this solution compared with many others here is that it works for any location in pretty much any type of variable.
John ZwinckJohn Zwinck163k1919 gold badges196196 silver badges316316 bronze badges
billbill
This program is to change any data bit from 0 to 1 or 1 to 0:
Peter Mortensen14.4k1919 gold badges8888 silver badges117117 bronze badges
Gokul NaathanGokul Naathan
If you're doing a lot of bit twiddling you might want to use masks which will make the whole thing quicker. The following functions are very fast and are still flexible (they allow bit twiddling in bit maps of any size).
Note, to set bit 'n' in a 16 bit integer you do the following:
It's up to you to ensure that the bit number is within the range of the bit map that you pass. Note that for little endian processors that bytes, words, dwords, qwords, etc., map correctly to each other in memory (main reason that little endian processors are 'better' than big-endian processors, ah, I feel a flame war coming on..).
Tim RingTim Ring
Peter Mortensen14.4k1919 gold badges8888 silver badges117117 bronze badges
thangavel
kendotwillkendotwill
If you want to perform this all operation with C programming in the Linux kernel then I suggest to use standard APIs of the Linux kernel.
See https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html
Note: Here the whole operation happens in a single step. So these all are guaranteed to be atomic even on SMP computers and are usefulto keep coherence across processors.
Peter Mortensen14.4k1919 gold badges8888 silver badges117117 bronze badges
Jeegar PatelJeegar Patel14.4k3434 gold badges122122 silver badges183183 bronze badges
Visual C 2010, and perhaps many other compilers, have direct support for bit operations built in. Surprisingly, this works, even the
sizeof()
operator works properly. So, to your question,
IsGph[i] =1
, or IsGph[i] =0
make setting and clearing bools easy.To find unprintable characters:
Note there is nothing 'special' about this code. It treats a bit like an integer - which technically, it is. A 1 bit integer that can hold 2 values, and 2 values only.
I once used this approach to find duplicate loan records, where loan_number was the ISAM key, using the 6-digit loan number as an index into the bit array. Savagely fast, and after 8 months, proved that the mainframe system we were getting the data from was in fact malfunctioning. Serial key virtual dj pro 8. The simplicity of bit arrays makes confidence in their correctness very high - vs a searching approach for example.
Felipe Augusto2,58844 gold badges1414 silver badges3232 bronze badges
user1899861
Use one of the operators as defined here.
To set a bit, used
Fahim Parkarint x = x | 0x?;
where ?
is the bit position in binary form.21.2k3434 gold badges139139 silver badges244244 bronze badges
JasonJason
sam msftsam msft
Variable used
value - Data
pos - position of the bit that we're interested to set, clear or toggle.
pos - position of the bit that we're interested to set, clear or toggle.
Set a bit:
Clear a bit:
Toggle a bit:
Felipe Augusto2,58844 gold badges1414 silver badges3232 bronze badges
Jeet ParikhJeet Parikh
Felipe Augusto2,58844 gold badges1414 silver badges3232 bronze badges
Sazzad Hissain KhanSazzad Hissain Khan17.5k99 gold badges7676 silver badges116116 bronze badges
How do you set, clear, and toggle a single bit?
To address a common coding pitfall when attempting to form the mask:
1
is not always wide enoughWhat problems happen when
number
is a wider type than 1
?x
may be too great for the shift 1 << x
leading to undefined behavior (UB). Even if x
is not too great, ~
may not flip enough most-significant-bits.To insure 1 is wide enough:
Code could use
1ull
or pedantically (uintmax_t)1
and let the compiler optimize.Or cast - which makes for coding/review/maintenance issues keeping the cast correct and up-to-date.
Or gently promote the
1
by forcing a math operation that is as least as wide as the type of number
.As with most bit manipulations, best to work with unsigned types rather than signed ones
chuxchux88k88 gold badges7979 silver badges165165 bronze badges
Joakim L. ChristiansenJoakim L. Christiansen
Let suppose few things first
num = 55
Integer to perform bitwise operations (set, get, clear, toggle).n = 4
0 based bit position to perform bitwise operations. - To get the
nth
bit of num right shiftnum
,n
times. Then perform bitwise AND&
with 1.
How it works?
- To set a particular bit of number. Left shift 1
n
times. Then perform bitwise OR|
operation withnum
.
How it works?
- Left shift 1,
n
times i.e.1 << n
. - Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e.
~ (1 << n)
. - Finally, perform bitwise AND
&
operation with the above result andnum
. The above three steps together can be written asnum & (~ (1 << n))
;
How it works?
To toggle a bit we use bitwise XOR
^
operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0. Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.
How it works?
- If the bit to toggle is 0 then,
0 ^ 1 => 1
. - If the bit to toggle is 1 then,
1 ^ 1 => 0
.
Recommended reading - Bitwise operator exercises
Pankaj PrakashPankaj Prakash
Try one of these functions in the C language to change n bit:
Or
Or
Peter Mortensen14.4k1919 gold badges8888 silver badges117117 bronze badges
VincetVincet
protected by PraveenSep 12 '14 at 11:57
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?