Beau Schwabe
- Joined Nov 7, 2019
- 186
I wasn't trying to start anything, YES, I should have AND'ed the mask to isolate the bit(s) of interest before XORing them. But seriously at a fundamental level such as bit manipulation, much of the logic is all the same no matter what language you are using.
BTW) Embedded C does allow for inline assembly capabilities which would allow any of those instructions to be applied.
When and Why Do We Need the AND Operation in extracting specific bits?
BTW) Embedded C does allow for inline assembly capabilities which would allow any of those instructions to be applied.
When and Why Do We Need the AND Operation in extracting specific bits?
Code:
Example1: (Need AND to read Bit)
Suppose the data you read has a decimal value of 38 and you wanted to only look at BIT 2
The Binary value for 38 is b'00100110'
Data = b'00100110'
So to look at BIT 2, you create a Mask with that bit set to a '1'
Mask = b'00000100'
When you AND the Data with your Mask the result will be 4 or the binary value of b'00000100'
If you want to determine if BIT 2 is a 1 or a 0 you just look to see if the result is greater than 0 or equal to 0.
If it's greater than 0 then BIT 2 is a 1 otherwise if the result was equal to 0 then BIT 2 is a 0.
---------------------------------------------------------------------------------------------------------------------------------
Example2: (Don't need AND to set BIT)
Let's say you wanted BIT 3 to be a 1 in the Same Data value of 38 without changing any of the other bits.
Data = b'00100110'
You would still create a Mask for BIT 3
Mask = b'00001000'
To set BIT 3 to a 1, Simply OR the Data with your Mask the result will be 46 or the binary value of b'00101110'
---------------------------------------------------------------------------------------------------------------------------------
Example3: (Need AND to clear BIT)
Let's say you wanted BIT 5 to be a 0 in the Same Data value of 46 without changing any of the other bits.
Data = b'00101110'
create a Mask for BIT 5
Mask = b'00100000'
Invert the Mask value by XORing it with b'11111111'
Inv_Mask = Mask XOR b'11111111' = b'11011111'
To set BIT5 to a 0, Simply AND the Data with your Inv_Mask the result will be 14 or the binary value of b'00001110'