在Python中复制Javascript按位运算 [英] Replicating Javascript bitwise operation in Python

查看:116
本文介绍了在Python中复制Javascript按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中复制一个简单的按位Javascript操作.

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

[Javascript]

[Javascript]

> 0xA867Df55
  2825379669
> 0xA867Df55 ^ 0
  -1469587627

[Python]

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

已阅读以下内容:

ruby​​与javascript中的按位OR

听起来这里的问题是Javascript中的0xA867Df55(2825379669)大于最大的有符号32位int(2147483647),这会导致意外的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.

然后邮件继续提示:

如果出于某种原因要在Ruby中重现,则可以将数字与1FFFFFFFF进行与"运算,以便仅对最低有效32位进行运算,然后对其进行"0"运算(这不会做任何事情,但会给您结果相同."

"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

我只需要在Python中复制Javascript行为即可.有人可以建议适当的按位运算吗?

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

谢谢.

推荐答案

如何从uint32转换为int32.

How about converting from uint32 to int32.

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

输出

-1469587627

或者如@Ashwini所建议的那样:

Or as @Ashwini suggests:

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

输出

-1469587627

这篇关于在Python中复制Javascript按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆