10

python实现java无符号右移

 2 years ago
source link: http://blog.wen2go.site/2022/01/16/python%E5%AE%9E%E7%8E%B0java%E6%97%A0%E7%AC%A6%E5%8F%B7%E5%8F%B3%E7%A7%BB/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python实现java无符号右移,python中只有右移>>和左移<<,为了实现java>>>

!!!如非必要,不要使用python复现java,好多坑… 使用js复现java代码更方便些

  • 另外python的左移存在一定的问题,当数据过大时,python左移的结果和其他语言不一致,可以使用下面的代码解决
#无符号右移
import ctypes

# 使用此函数处理左移问题
def int_overflow(val):
maxint = 2147483647
if not -maxint-1 <= val <= maxint:
val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
return val

# 模拟java的无符号右移 >>>
def unsigned_right_shift(n,i):
# 数字小于0,则转为32位无符号uint
if n<0:
n = ctypes.c_uint32(n).value
# 正常位移位数是为正数,但是为了兼容js之类的,负数就右移变成左移好了
if i<0:
return -int_overflow(n << abs(i))
#print(n)
return int_overflow(n >> i)

  • int_overflow(1701273967 << 3) # 结果:725289851
    1701273967 << 3 # 直接左移返回结果:13610191736 (py2 会带个L)

    unsigned_right_shift(-160556357, 3) # 结果:516801367 和java执行结果一致

    java代码可以百度一个在线运行java的工具


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK