I've searched for this, but my results were unsatisfactory, probably because of how hard it is to word. I have one object, state
, which is a byte
that represents which parts of my object are to be rendered when observed, and a method, disableParts(byte partsToDisable)
, which will turn off all bits in state
that are ON in partsToDisable
. How do I achieve this functionality in bitwise operations? (that is, only using AND
, OR
, XOR
, NOT
, LSHIFT
, ARSHIFT
, LRSHIFT
, PLUS
, MINUS
, MULTIPLY
, and/or DIVIDE
and basic program functions such as loops and branching statements)
For a bit of clarity, here is a visual representation of my desired functionality:
0010 0101 (current state, 37 in this example)
? 1010 0010 (bits to disable, -94 in this example)
============
0000 0101 (new state, 5 in this example)
and a dummy class (in Java because that's how I think, but the solution can be any language or pseudo-code):
class BitThoughts
{
byte state;
public void doIt()
{
state = 0b00100101;
System.out.println("Initial state: " + state);
disableParts(0b10100010);
if (state == 0b00000101)
System.out.println("Success! New state is " + state);
else
System.out.println("Failure! New state is " + state);
}
public void disableParts(byte partsToDisable)
{
//Do magic to state
}
}
Just so no one derps as hard as I did... here's the answer:
0010 0101 (current state, 37 in this example)
& ~1010 0010 (bits to disable, -94 in this example)
=============
becomes:
0010 0101 (current state: 37)
& 0101 1101 (inverted bits to disable: 93)
=============
0000 0101 (new state, 5 in this example)
and the solution in Java:
public void disableParts(byte partsToDisable)
{
state &= ~partsToDisable;
}
The idea is to use bitwise <<, & and ~ operators.
Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
Use the bitwise AND operator ( & ) to clear a bit.
The Bitwise Xor operation treats the sign bit as it would any other bit. If one or both inputs for a pixel location are negative, the output is negative; if both inputs are positive, the output is positive.
What you need to do is invert the bits (bit-wise NOT) in partsToDisable
so you end up with a mask where the 1's are the bits to be left alone and the 0's are the bits to be turned off. Then AND this mask with the state value.
public void disableParts( byte partsToDisable)
{
state = state & (~partsToDisable);
}
If you just invert the bits of the parts, you can just AND it with the state
void disableParts(byte parts) {
byte invertOfParts = 0b11111111 - parts;
state &= invertOfParts
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With