Python Bitshift 32 Bit Constraint [duplicate]

跟風遠走 提交于 2019-12-04 06:17:32

问题


Possible Duplicate:
Problem in calculating checksum : casting int to signed int32

This should be a relatively easy answer, I just don't really know how to search for it...I got a few semi-relevant things, but nothing that fits what I'm trying to do.

>>> 1171855803 << 7
149997542784L # I want -326312576

In other words, treat the number as an integer and don't allow it to convert to a long. How would I do this?

I tried the solution in this question:

>>> x = 0xFFFFFFFF & (1171855803 << 7)
>>> if x > 0x7FFFFFFF: print -(~(x - 1) & 0xFFFFFFFF)
else: print x

-326312576L # yay!

It works!


回答1:


May not be the best answer, but this works...

import numpy as np
np.int32(1171855803) << 7



回答2:


You could try

import ctypes
a=ctypes.c_int32(1171855803)
a.value<<=7
print a

which gives: c_int(-326312576)

It seems to allow platform specific bit-manipulations. I am not sure about efficiency.



来源:https://stackoverflow.com/questions/7201207/python-bitshift-32-bit-constraint

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