I'm receiving a 3-byte message back from a serial device when I send it a query in my C# application. The entire message should have at most one bit set, e.g. $04 00 00
is fine, but not $04 01 00
or $05 00 00
.
Bit-shifting and checking each bit is one solution but perhaps there is something more elegant? We can check each byte to see if it's a power of two but I can't come up with a way which looks nicer (not sure about efficiency in these cases either).
As an extension to the problem, I need to match each possible value to an output message, e.g.:
$01 00 00: Button A pressed
$00 02 00: Lever B pulled
$00 00 04: Switch C activated
A case statement is a simple solution, but once again, wondering if there's a pretty way of doing this as well.
There is one clever trick to check if byte has more one bit set. n & (n - 1) != 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments