2

I am trying to do this :

print 17593028247552 ^ 909522486

The result must be 67450422(as is in javascript) but I am getting 17592253494838L

Please help me ! Thanks in advance :)

2 Answers 2

7

Python 2's long type (or int in Python 3) can grow as large as they need to, but it looks like you want a 32 bit result.

You just need to mask the result so you only get the low 32 bits of the result. And I guess that since you're on Python 2 you should also convert it from long to int.

>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422
Sign up to request clarification or add additional context in comments.

4 Comments

I might be tempted to put it as 2 ** 32 - 1 to make it a bit more obvious as to the number of bits the result is being rounded to (and a quick change if you wanted to round it to 64 for instance...)
@Jon Fair enough. Maybe I'm old-fashioned, but I like the hex form. :) OTOH, Python will evaluate 2 ** 32 - 1 when it compiles the script, so there's no real advantage in using the hex form.
I also happen to like the hex-form - I just wouldn't want to type it for 128 bits :) (I'd probably get it wrong for a start...)
Thanks a lot. That helped
0

I just used Windows calculator:

100000000000000110010001100110000000000000000  = 17593028247552d
000000000000000110110001101100011011000110110  =      909522486d
100000000000000000100000001010011011000110110  = 17592253494838d

Looks like JavaScript is wrong. It's probably narrowing to 32 bit or something before doing XOR. Python is arbitrary precision on integers.

Edit: As the other answer points out, if you're still using Python 2 (don't do that!) only long is arbitrary precision; the precision of int can vary but it's usually 64 bit. In Python 3 there is only one integer type and it's always arbitrary precision.

1 Comment

Python can be 32 bit or 64 bit. Some of us are still running 32 bit machines... In a 32 bit build, Python 2 int is 32 bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.