Re:Two's complement – You beauty
by zardeh on Wednesday January 11, 2017 @01:23AM
(#13372157)
The python result should be expected. Python's integer type isn't sized, that is python will happily give you factorial(100), despite it being much larger than 64 bits. It can't then give you twos complement, because it can't know the size with which to complement the two.
[ Parent
| on HN ]
Re:Two's complement – You beauty
by brandonbloom on Wednesday January 11, 2017 @05:51AM
(#13373072)
That's a reasonable tradeoff for Python, but it's worth noting that there is a way to deal with this.
Quoting from http://reference.wolfram.com/language/tutorial/IntegerAndNum...
Bitwise operations are used in various combinatorial
algorithms. They are also commonly used in manipulating
bitfields in low‐level computer languages. In such
languages, however, integers normally have a limited
number of digits, typically a multiple of 8. Bitwise
operations in the Wolfram Language in effect allow
integers to have an unlimited number of digits. When an
integer is negative, it is taken to be represented in
two's complement form, with an infinite sequence of ones
on the left. This allows BitNot[n] to be equivalent
simply to (-1 - n).Yes, but how would you print that infinite sequence of 1s?
same as the infinite number of zeros in front of a positive number.
Re:Two's complement – You beauty
by AstralStorm on Wednesday January 11, 2017 @08:15AM
(#13373673)
Just trimming 1s would be ambiguous. Is b11 3 or -2?
You would have to add a 0 prefix to all positive numbers or some other to negative.
Re:Two's complement – You beauty
by brandonbloom on Wednesday January 11, 2017 @01:42PM
(#13376325)
Just prefix a + or - just like you do for base 10.
So then it would not make much of a difference anymore with what Python does. Which was what they wanted to avoid.
Re:Two's complement – You beauty
by throwawayish on Wednesday January 11, 2017 @08:25AM
(#13373713)
Indeed. For this use case to_bytes would be correct (writing this in the most verbose way possible :)
>>> (-352).to_bytes(length=4, byteorder='big', signed=True).hex()
'fffffea0'
>>> (352).to_bytes(length=4, byteorder='big', signed=True).hex()
'00000160'
Note how well-defined and independent of the actual machine this conversion is. Since you define everything - length, byte order and whether to get two's complement or not - you'll get the same output everywhere.
Re:Two's complement – You beauty
by yogeswarant on Wednesday January 11, 2017 @01:26AM
(#13372163)
Thanks. Good to know this.
Bitwise opetations assume an infinite number of 1s on the left for negative numbers (2s compliment) e.g., ~-1 == 0 (-1 is an infinite number of 1s that are converted to 0 by ~ (invert) operator ).
3 == 011
2 == 010
1 == 001
0 == 000
-1 == ..111
-2 == ..110
-3 == ..101