Ask Your Question
1

Bitwise NOT Operator for Sage?

asked 2014-08-18 23:30:28 +0100

david8381 gravatar image

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?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
3

answered 2014-08-19 00:21:15 +0100

tmonteil gravatar image

updated 2014-08-19 00:22:30 +0100

The bitwise not in Python is supposed to be ~(see https://wiki.python.org/moin/BitwiseO... 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.

edit flag offensive delete link more
1

answered 2014-08-20 11:42:54 +0100

slelievre gravatar image

As 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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2014-08-18 23:30:28 +0100

Seen: 2,679 times

Last updated: Aug 20 '14