• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

binary question

Deeko

Lifer
I'm fairly certain this is more of a math quesion than a programming question, that's why I'm posting this here.

I'm given an 8-bit error code by a device and each bit is a separate flag, so I need to parse them out. I know there is some operation to perform...bit shift or xor or something....but for the life of me I can't remember and google is no help. Anyone?

Thanks
 
Do a series of bitwise ANDs to extract each bit.

For example, to extract the value of the bit in the second position, do a bitwise AND with 00000010. If the result is decimal 2, the second bit was set.
 
As kranky said, you're talking about bitwise operations. Some simply call it "bit twiddling" as well. Anyway, here are the basic "rules":

To test for a bit, you bitwise and it against a mask:

mask = 0x01
value = 1
if (value & mask == value) it's on

To set a bit:

mask = 0x01
value = 0
value |= mask

To toggle a bit (on if off, off if on):

mask = 0x01
value = 1
value ^= mask

To turn off a bit:

mask = 0x01
value = 1
value &= ~mask

That about covers everything you'd need to do for simple error code checking. The bitwise operators in the examples above are valid for most languages with a C-derived syntax.
 
Back
Top