Archived

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

Yanroy

bitwise operator problem

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

Yanroy@usa.com

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites