Replicating Javascript bitwise operation in Python

瘦欲@ 提交于 2019-12-10 13:55:21

问题


I'm trying to replicate a simple bitwise Javascript operation in Python.

[Javascript]

> 0xA867Df55
  2825379669
> 0xA867Df55 ^ 0
  -1469587627

[Python]

>>> 0xA867DF55
2825379669L
>>> 0xA867DF55 ^ 0
2825379669L

Having read the following:

Bitwise OR in ruby vs javascript

it sounds like the issue here is that 0xA867Df55 (2825379669) in Javascript is larger than the largest signed 32-bit int (2147483647), which is causing an unexpected Javascript result.

The mail then goes on to suggest:

"If for some reason you wanted to reproduce that in Ruby, you would AND your number with 1FFFFFFFF so you're only operating on the least significant 32 bits and then OR it by 0 (which does nothing but would give you the same result)."

But if I try this:

>>> (0xA867DF55 & 0x1FFFFFFF) ^ 0
141025109L

I simply need to replicate the Javascript behaviour in Python. Can anyone suggest an appropriate bitwise operation ?

Thanks.


回答1:


How about converting from uint32 to int32.

import struct
print struct.unpack('i', struct.pack('I', 0xA867Df55))[0]

OUTPUT

-1469587627

Or as @Ashwini suggests:

import ctypes
print ctypes.c_int(0xA867DF55 ^ 0).value

OUTPUT

-1469587627


来源:https://stackoverflow.com/questions/17102767/replicating-javascript-bitwise-operation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!