#### Archived

This topic is now archived and is closed to further replies.

# bitwise operator problem

This topic is 5615 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''m trying to flip bit 3 of a byte depending on the value of a bool. This is because this byte is being sent serially to external hardware that is very memory-limited, so sending it as its own byte isn''t really an option. It seems to only work about 1 in 10 times, completely randomly. The rest of the time, the Command byte remains unchanged. Maybe there''s a flaw in my logic? I''m 99% certain that the problem isn''t in communicating with the external circuitry. Here''s my code:
bool CStampCtrl::Enable(bool Enabled)
{
// set Command bit 3 = Enabled regardless of current state and without changing state of other bits

Command |= CF_ENABLE; // CF_ENABLE = 0x08

Command ^= CF_ENABLE;

if (Enabled)
Command |= CF_ENABLE;

NewDataWaiting = true;
return true;
}
--------------------

You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming
You are unique. Just like everybody else.
"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor

##### Share on other sites
Okay, let''s examine your code. I''m assuming that CF_ENABLE is properly set to 0x08, and that Command is a char.

Command |= CF_ENABLE

Okay, so bit three is now ALWAYS SET, regardless of its previous value.

Command ^= CF_ENABLE

Since bit three was already set, it is now ALWAYS UNSET.

if(Enabled) Command |= CF_ENABLE

Okay, so if "Enabled" is true, then bit three is set; otherwise, bit three is unset.

Your code looks fine, but could be more concisely and clearly written as:
bool CStampCtrl::Enable(bool Enabled){Command |= CF_ENABLE; // CF_ENABLE = 0x08        if(Enabled)        {		Command |= CF_ENABLE;	}        else        {		Command &= ~CF_ENABLE;        }	NewDataWaiting = true;	return true;}

This could be further improved if the state of bit three of Command were known already.

Anyways, this code fragment appears fine. The only way to be sure is to step through it with a debugger.

How appropriate. You fight like a cow.

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5
frob
12

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633663
• Total Posts
3013236
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!