[TOC]
python中整数是不限位数的,所以是不会溢出的。位移时符号位不变!
64位long整数:
大数: 00000000000000000000000000000011111111111111111111111111111111111
左移32:11111111111111111111111111111111111
右移32: 000000000000000000000000000000
代码:
System.out.println( Long.toBinaryString(0x00000000FFFFFFFFL >>32));
System.out.println( Long.toBinaryString(0x00000000FFFFFFFFL <<32>>>32));
大数:00000000000000000000000000000000011111111111111111111111111111111
左移32:01111111111111111111111111111111100000000000000000000000000000000
右移32:00000000000000000000000000000000000000000000000000000000000000000
bstr = lambda x, l: ”.join((‘1’ if x & (1 << i) else ‘0’ for i in range(l, -1, -1)))
print(bstr(0x00000000FFFFFFFF, 64))
print(bstr(0x00000000FFFFFFFF >> 32, 64))
print(bstr(0x00000000FFFFFFFF << 32, 64))
由于有差异,在做算法时要细心一些。这里给出一些代码
# 模仿java的左移和右移32位。
# 注意,没有经过严格的测试,不要随意用于生产服务器。
# 这里方法只适合把64位转换为32位
def int_overflow(val):
maxint = 2147483647
if not -maxint - 1 <= val <= maxint:
val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
return val
def unsigned_right_shitf(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)
def unsigned_left_shitf(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 & (2**i-1)) # 左移不行。
#测试代码
print(0x00000000FFFFFFFF >> 32)
print(0x00000000FFFFFFFF << 32)
print(unsigned_right_shitf(key, 32))
print(unsigned_left_shitf(key, 32))
big=0x123456781234567812345678
b8=big & 0xFF #取低8位
b16=big & 0xFFFF # 取低16位
结果都是正数
[1] https://www.cnblogs.com/zhengyun_ustc/archive/2009/10/14/shifting.html
[2] https://www.jianshu.com/p/24d11ab44ae6