What is the best way to check this famous equation:
0x2b || ~0x2b == 0xff
Mathematica doesn't seem to have a handy bitwise negation operator.
The best thing I did come up was:
FromDigits[IntegerDigits[16^^2B, 2, 8]
~BitOr~(IntegerDigits[16^^2B, 2, 8] /. {1 -> 0, 0 -> 1}), 2] == 16^^FF
which is rather terse. Or:
2^^00101011~BitOr~2^^11010100 == 16^^FF
which is ok. But it's not the same.
My naive hope was that something like this would work but it doesn't:
16^^2B~BitOr~BitNot@16^^2B == 16^^FF
Which yields False and reveals that I do not understand what bitwise negation in Mathematica parlance means...
I had hoped that BitNot[16^^2B] would yield 16^^D4, but I was utterly wrong. How can you force Mathematica to use bytes? Because IntegerDigits[16^^2B,2,8] yields {0, 0, 1, 0, 1, 0, 1, 1} which is ok, but IntegerDigits[BitNot[16^^2B], 2, 8] yields {0, 0, 1, 0, 1, 1, 0, 0}.
Apparently not really a bitwise negation.
Help, tips, etc. appreciated.
EDIT:
So due to Daniel Lichtblau's answer the best result so far might be:
NOT[bits_Integer, len_Integer: 8] /; bits >= 0 && len >= 0 := BitXor[bits, 2^len - 1]
OR = BitOr
16^^2B~OR~NOT@16^^2B == 16^^FF
:) Hilarious!
EDIT 2
I'd say the BitNot should have an optional argument, if 2's-complement is wanted, defaulting to True. As such:
protected = Unprotect[BitNot];
$BitNotActive = True;
Options[BitNot] = {Compl -> True, Len -> 8};
BitNot[n_Integer, OptionsPattern[]] /; $BitNotActive :=
Block[{$BitNotActive = False},
If[OptionValue[Compl], BitNot[n],
BitXor[n, 2^OptionValue[Len] - 1]]
]
Protect[Evaluate[protected]];
So the big question (which is actually no question at all, since it's always true...) in Mathematica would become:
16^^2B~BitOr~BitNot[16^^2B, Compl -> False] == 16^^FF
I demand overloaded operators and number representation without the "base^^" syntax!
0x2B~OR~NOT@0x2Bshould give b111111 which is different from 0xff. You think a question whose answer would change the expected output is philosophical? – Rojo Jan 24 '13 at 18:12In[3]:= Internal`UnsignedBitNot[43,8]Out[3]= 212In[4]:= $Version
– Daniel Lichtblau Jan 24 '13 at 20:54Out[4]= 5.2 for Linux (September 17, 2006)I no longer recall why it was discarded. Maybe because it was too well hidden to get any use. I think this is the first time I've seen it requested.