Toggle specific bit in 32 bits variable

A forum devoted to the discussion of all topics having to do with scripting and other advanced programming using iX Developer.
Post Reply
DeFacto
Posts: 3
Joined: Mon Jul 07, 2014 11:38 pm

Toggle specific bit in 32 bits variable

Post by DeFacto »

Hello,

To read a specific bit in variable - expression is used, but is there a way to toggle specific bit in variable?

Chris D
Posts: 6
Joined: Tue Aug 05, 2014 10:53 am

Re: Toggle specific bit in 32 bits variable

Post by Chris D »

Hi,

you can use script and the XOR operator (^)
For example:

Gobals.Tags.myvar.Value = Gobals.Tags.myvar.Value ^ (1<< 5);

to toggle bit 5.

regards
Chris

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Toggle specific bit in 32 bits variable

Post by AMitchneck »

FYI, another way of doing Chris D's suggestion:

Globals.Tags.myvar.Value ^= 1 << 5;

this code also toggles bit 5 using and exclusive-or. One warning I will give: this method reads what current bits are set, toggles the one bit, then writes all bits back. If other bits are changed in the mean time by the controller or whatever that change will be lost (or improperly translated as a toggle depending on how you are using them).
Adam M.
Controls Engineer
FlexEnergy

DeFacto
Posts: 3
Joined: Mon Jul 07, 2014 11:38 pm

Re: Toggle specific bit in 32 bits variable

Post by DeFacto »

Thank you for the replies.

Post Reply