ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 20 Aug 2014 11:42:54 +0200Bitwise NOT Operator for Sage?https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/0b1000 & 0b1001 (AND)
0b1000 | 0b1001 (OR)
0b1000 ^^ 0b1001 (XOR)
All of these work as bitwise operators on the command line -- but how do I do bitwise NOT? Mon, 18 Aug 2014 23:30:28 +0200https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/Answer by slelievre for <p>0b1000 & 0b1001 (AND)
0b1000 | 0b1001 (OR)
0b1000 ^^ 0b1001 (XOR)</p>
<p>All of these work as bitwise operators on the command line -- but how do I do bitwise NOT? </p>
https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/?answer=23845#post-id-23845As a complement to @tmonteil's answer, you can append 'r' (for 'raw') to some input to prevent it from being preparsed, without globally turning the preparser off.
Using the same example as @tmonteil:
sage: ~0b1000r
-9
Wed, 20 Aug 2014 11:42:54 +0200https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/?answer=23845#post-id-23845Answer by tmonteil for <p>0b1000 & 0b1001 (AND)
0b1000 | 0b1001 (OR)
0b1000 ^^ 0b1001 (XOR)</p>
<p>All of these work as bitwise operators on the command line -- but how do I do bitwise NOT? </p>
https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/?answer=23825#post-id-23825The bitwise ``not`` in Python is supposed to be ``~`` (see https://wiki.python.org/moin/BitwiseOperators about how negative numbers are encoded), but Sage's preparser first transforms ``0b1000`` as an element of ``ZZ`` for which the action of ``~`` is the multiplicative inverse:
sage: ~0b1000
1/8
This is because, in Sage:
sage: 0b1000.parent()
Integer Ring
sage: preparse("0b1000")
"Integer('1000', 2)"
To get the python behaviour, you can either turn the sage preparser off:
sage: preparser(False)
sage: ~0b1000
-9
or explicitely use python ``int``:
sage: ~int(0b1000)
-9
Another workaround is to notice that ``not a`` is the same as ``a xor 1``.
Tue, 19 Aug 2014 00:21:15 +0200https://ask.sagemath.org/question/23823/bitwise-not-operator-for-sage/?answer=23825#post-id-23825