Logic union: XOR, NAND and NOR
I need a XOR to clear a specific bit in a 2-byte integer. Say, bit 9 (256).
It must be set low regardless of its state without changing any other bit. This means XORring it with (1 << 9). Would be simple, except that Max does not have XOR operator, nor a NAND or NOR, from which a XOR could be constructed.
Help, anybody!
Hello DAN LAUT,
Max has a bitwise AND operator [&]. If you need to clear a bit you bitwise 'AND' your integer with another one that has all bits set to 1 and the one you need to clear to 0.
Another option would be to do it in JavaScript (inside an [js]-object ). You'll have all bitwise operators available there.
To set the bit hi: | 2^ [bitnr].
To set the bit lo: & -((2^ [bitnr])+1)
I'd prefer a XOR, which would reduce it to a single operation either way, but one has to row with the oars one's got.
what is wrong with doing it arithmetically?
@DAN i n that case js is probably the best way to go
The problem with arithmetic ops is that they also affect other bits.
To simulate a XOR, AND the input with the reciprocal of the bit(s) to change.
Then OR the result with the bit(s) to set.
In the case of bits 4-6, for example, first AND with -113 (0x...FF8F). This sets bit 4-6 to 0 while preserving the state of the other bits in the input.
Then OR the result with ([int 0-7] << 4) to set the bits to the desired value.
So: