简体   繁体   English

大整数上的位操作左移 Python

[英]Bit operation Left Shift Python on big integers

I am trying to implement a left bit shift on python with big integers.我正在尝试使用大整数在 python 上实现左位移。 Because of their size, I want to stock their bit value on a file and work on the file after, as far as the bit string it too big for my RAM.由于它们的大小,我想将它们的位值存储在文件中并在之后处理文件,就位字符串而言它对于我的 RAM 来说太大了。 However, I am facing problem deleting the N first bits of the int without using its binary representation, as far as I can't.但是,我在不使用二进制表示的情况下删除 int 的前 N ​​位时遇到问题,但我不能。 Here is what I did so far:这是我到目前为止所做的:

def __lshift(self, n, d):
    N = n.bit_length()
    if N > 2**20: # n is big and we have to use files
        temp = open('bin.tmp','w')
        while N > 2**20:
            n_ = n >> 20 # Take the 20 first bits of n
            temp.write(bin(n)[2:])
            # Here I would like to delete 20 first bits of n
    else:
        bin_ = bin(n)[2:]
        bin_ = bin_[:N-d] + bin_[d:]
        return int(bin_,2)

Thanks for your help !谢谢你的帮助 !

Here is the solution I finally found :这是我最终找到的解决方案:

def lshift(n,d):
def one_turn(n):
    N = n.bit_length()
    end = n >> N-1
    begin = (n & ((1 + (1 << N-1) - 1) ^ ((1 << N) - 1))) << 1
    return begin + end

for i in range(d):
    n = one_turn(n)
return n

Finally easier than what I was trying to do :)最后比我想做的更容易:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM