-
Notifications
You must be signed in to change notification settings - Fork 57
Two's complement semantics for bitwise operators? #3
Comments
I believe two's complement is the intuitive semantics for bitwise ops. This is what Java, Python and GMP specify (https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html, https://wiki.python.org/moin/BitwiseOperators, https://gmplib.org/manual/Integer-Logic-and-Bit-Fiddling.html). Efficiency depends on what the underlying representation is. If it is two's complement (Java BigInteger), it is super-fast. If it is sign-magnitude (Python, GMP), then one needs to convert to two's complement, do the bitwise op and convert back (e.g., see Python's implementation here: https://github.com/python/cpython/blob/master/Objects/longobject.c#L4406). Even that should be cheap-ish. |
Note: I think that for small integers, Python's representation is also two's complement, so bitwise ops on those are very fast. (For long integers, the cost of complements should not matter much because the allocation and loads/stores will dominate.) |
OK, the specification is clear that we do have this infinite two's complement semantics. Anyone, if you discover more information here, let's reopen this bug and discuss it. Closing for now. |
Should this line in the spec be updated? It says “one’s complement”. Lines 266 to 269 in f26c2c7
|
@chharvey I believe the statement is correct. bitwise-not == ones' complement; unary-minus == two's complement. (According to Wikipedia, the correct spelling is "ones' complement", not "one's complement", so that's a nit that could be fixed.) |
@jakobkummerow But doesn’t the bitwise-not operator use two’s complement? e.g.:
I thought |
What the bitwise-not operator (conceptually) does is to invert every bit, and "inverting every bit" is how "ones' complement" is defined. (What it actually does in all implementations I know of is to compute Sure, if you have Saying that "the ones' complement value of 6 is -7" would be illogical -- the accurate statement is "the ones' complement value of 6 is the same bit pattern as the two's complement value of 7". The It's a bit confusing :-) |
It goes way over my head! Thanks for the explanation. 😃 |
Are two's complement semantics for bitwise operations the best ones? Are they very efficiently implementable? cc @jaro-sevcik
The text was updated successfully, but these errors were encountered: